[CSS] fixed 子元素的 z-index

1. 现象

下拉框设置了 z-index1000,却没有遮住底下 z-index5 的内容。

1.1 最简示例

(1)HTML

<div class="fixed">
    <div class="dropdown">
        z-index: 1000;
    </div>
</div>
<div class="error">
    z-index: 5;
</div>

(2)CSS

body {
    margin: 0;
}

.fixed {
    position: fixed;

    z-index: 3;
}

.dropdown {
    position: absolute;
    background: gray;
    width: 300px;
    height: 300px;

    z-index: 1000;
}

.error {
    position: absolute;
    background: red;
    width: 100px;
    height: 100px;
    left: 250px;
    top: 250px;

    z-index: 5;
}

1.2 效果

其中灰色部分表示下拉框,z-index1000
红色部分,z-index5

2. 原因

Chrome 22 之后positionfixed的元素会创建一个新的层叠上下文(stacking context),
而子元素的 z-index 值,只在父级层叠上下文中才中有意义。

Importantly, the z-index values of its child stacking contexts only have meaning in this parent.

Everyone knows and loves the z-index for determining depth ordering of elements on a page. Not all z-indexes are created equal, however: an element's z-index only determines its ordering relative to other elements in the same stacking context.

Within a local stacking context, the z-index values of its children are set relative to that element rather than to the document root. Layers outside of that context — i.e. sibling elements of a local stacking context — can't sit between layers within it.

3. 修复方案

.fixed {
    ...
    z-index: 6;
}

参考

Stacking Changes Coming to position:fixed elements
The Stacking Context
CSS stacking contexts: What they are and how they work

推荐阅读更多精彩内容

  • 看似简单的表象实际上并没有想象的简单。最近不知道啥情况,同事之间流行了一句话“这还不简单啊”。甭管遇见什么问题都是...
    培佑哥阅读 1,081评论 0 6
  • Sola Scriptura and the Regulative Principle of Worship Br...
    DanielHe阅读 4,889评论 1 11
  • 保持这个姿势5到10个呼吸 每个动作20次,循环2组,组间休息1分钟 每个动作20次,循环2组,组间休息1分钟
    翻过那座山阅读 92评论 0 0
  • 勿忘初心,方得始终!不要让自己陷入悲观的绝境!理想,目标是你的动力!懒人病多,饿死懒的,饱死勤的!
    风清杨阅读 29评论 0 1
  • 一路走来,非常感谢那个不放弃的自己,和在这过程中给与我鼓励和嘲笑的人。起起伏伏的过程,就像是人生一样,有的人说健身...
    牛油果丸子阅读 197评论 0 7