z-index属性,无效和有效

图片描述

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    * {padding: 0; margin: 0;}
    .wrap {width: 200px; height: 200px; border: 10px solid yellow; padding: 10px; margin: 50px; background: red; position:relative;}
    .a {width: 50px; height: 50px; background: black; position: absolute; top:0; right: 0;  z-index: 9999; float: left;}
    img {position: absolute; top:0; left: 0; z-index: 999;}
    </style>
</head>
<body>
    <div class="wrap">
        <img style="width:100%; height:100%;" src="v10.jpg" alt="">
        <div class="a"></div>
    </div>

<!-- 
z-index无论设置多高都不起作用情况

这种情况发生的条件有三个:

1、父标签 position属性为relative;

2、问题标签无position属性(不包括static);

3、问题标签含有浮动(float)属性。 -->
</body>
</html>
阅读 7.1k
8 个回答

https://www.w3.org/TR/2011/RE...

if 'position' has the value 'absolute' or 'fixed', the box is absolutely positioned, the computed value of 'float' is 'none'.

所以 position 为 absolute 会让 float 无效。

其次,看渲染顺序

  1. the background and borders of the element forming the stacking context.

  2. the child stacking contexts with negative stack levels (most negative first).

  3. the in-flow, non-inline-level, non-positioned descendants.

  4. the non-positioned floats.

  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.

  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.

  7. the child stacking contexts with positive stack levels (least positive first).

可以看到,float 在中间,z-index 正值的 absolute 在最后,所以总会盖住 float。

浮动和定位都设置的时候,浮动没生效。div.a标签和img标签都是absolute,谁的层级(z-index)高,谁在上面显示。

z-index无论设置多高都不起作用情况

这种情况发生的条件有三个:

1、父标签 position属性为relative;

说明 情况1这个是指多个父元素之间都设置relative,其子元素之间比较的情况,而不是单个父元素设置relative,然后其内部子元素之间互相比较。

应该是position:absolute优先级大于float

楼上正解 可采纳

z-index要在定位元素生效

你的z-index属性在两个同级绝对定位元素身上,当然后面的生效了。要改变层级;改变属性的值,正数和负数都可以。

1.如果“位置”的值为“绝对”或“固定”,则该框绝对定位,“浮动”的计算值为“none”。
2.其次,看渲染顺序

  • 元素的背景和边界构成了叠加上下文

  • 这个子堆的上下文是负的堆栈级别(首先是负的)。

  • 内流、非直线、非定位的后代。

  • non-positioned漂浮。

  • 流的、内联的、非定位的后代,包括内联表和内联块。

  • 在堆栈级别0和堆栈级别0的位置上的子堆栈上下文。

  • 孩子堆积的上下文有正的堆栈级别(最少是正面的)。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题