即使用z-index,伪元素也与原始元素重叠

时间:2018-05-08 12:38:36

标签: css css3 pseudo-element

拜托,任何人都可以向我解释一下:为什么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>
&#13;
&#13;
&#13;

在这种情况下,伪元素不应该与原始元素重叠,对吗?

我玩了一下(dah!),发现z-index在伪元素本身上的作用是正确的:

:afterz-index: 0> :beforez-index: 0

:afterz-index: -1< :beforez-index: 1

那到底是怎么回事?!

1 个答案:

答案 0 :(得分:0)

我认为这是因为“堆叠背景”。堆叠上下文就像一副牌,您可以在一个牌组中控制分层顺序,但如果您有两个牌组,则一个分层顺序不会影响另一个的分层顺序。伪元素(::before::after)与主元素本身处于不同的堆叠上下文中,因此,这些伪元素的z-index不能与{@ 1}}主要元素。

来自 MDN

  

每个堆叠上下文完全独立于其兄弟姐妹:   处理堆叠时仅考虑后代元素

通过更改HTML结构以使所有呈现的元素成为彼此的兄弟元素和共同父元素的后代,z-index可以正常工作。

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;
}

相关问题