拜托,任何人都可以向我解释一下:为什么z-index
无效?
html,body,div {margin:0;padding:0;}
.bz {
position: absolute;
z-index: 1;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 25px;
height: 25px;
border: 2px solid #000;
background: #0f0;
border-radius: 50%;
}
.bz:before {
content: '';
display: block;
position: absolute;
z-index: -1;
bottom: 0;
right: 0;
width: 8px;
height: 25px;
transform: rotate(315deg);
background: #f00;
}
.bz:after {
content: '';
display: block;
position: absolute;
z-index: -1;
bottom: 0;
right: 0;
width: 8px;
height: 25px;
transform: rotate(45deg);
background: #00f;
}
<div class="bz">
</div>
在这种情况下,伪元素不应与原始元素重叠,对吧?
我玩了一下(dah!),发现z-index
在伪元素本身上的作用是正确的:
:after
(z-index: 0
)>
:before
(z-index: 0
)
:after
(z-index: -1
)<
:before
(z-index: 1
)
那么到底是怎么回事?!
我相信这是因为“堆叠背景”。堆叠上下文就像一副牌,您可以在一个牌组中控制分层顺序,但如果您有两个牌组,则一个分层顺序不会影响另一个的分层顺序。伪元素(::before
和::after
)与主元素本身处于不同的堆叠上下文中,因此,这些伪元素的z-index
与主元素的z-index
不可比。
来自MDN:
每个堆叠上下文完全独立于其兄弟:在处理堆叠时仅考虑后代元素。
通过更改HTML结构以使所有呈现的元素成为彼此的兄弟元素和共同父元素的后代,z-index
可以正常工作。
#wrapper {
position:absolute;
top:50%;
left:50%;
}
.bz {
display: block;
width: 25px;
height: 25px;
border: 2px solid #000;
background: #0f0;
border-radius: 50%;
z-index: 1; /* Not actually necessary because the other z-indexes now apply */
}
.red {
content: '';
display: block;
position: absolute;
z-index: -1;
bottom: 0;
right: 0;
width: 8px;
height: 25px;
transform: rotate(315deg);
background: #f00;
}
.blue {
content: '';
display: block;
position: absolute;
z-index: -1;
bottom: 0;
right: 0;
width: 8px;
height: 25px;
transform: rotate(45deg);
background: #00f;
}
<div id="wrapper">
<!-- Now, all the child elements are in the same stacking context. -->
<div class="bz"></div>
<div class="red"></div>
<div class="blue"></div>
</div>