CSS

[CSS] fixed 子元素的 z-index

2019-04-01  本文已影响6人  何幻

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

上一篇 下一篇

猜你喜欢

热点阅读