1. 現(xiàn)象
下拉框設(shè)置了 z-index
為 1000
婚被,卻沒(méi)有遮住底下 z-index
為 5
的內(nèi)容空厌。
1.1 最簡(jiǎn)示例
(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-index
為1000
,
紅色部分泳挥,z-index
為5
琅关。
2. 原因
Chrome 22 之后,position
為fixed
的元素會(huì)創(chuàng)建一個(gè)新的層疊上下文(stacking context)哗伯,
而子元素的 z-index
值荒揣,只在父級(jí)層疊上下文中才中有意義。
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. 修復(fù)方案
.fixed {
...
z-index: 6;
}
參考
Stacking Changes Coming to position:fixed elements
The Stacking Context
CSS stacking contexts: What they are and how they work