如果我们使用z-index结合position:absolute;它可能将::之前的元素放在本身下.在
another question(
jsfiddle.net/Ldtfpvxy)有一个很好的例子.
基本上
<div id="element"></div> #element { position: relative; width: 100px; height: 100px; background-color: blue; } #element::after { content: ""; width: 150px; height: 150px; background-color: red; /* create a new stacking context */ position: absolute; z-index: -1; /* to be below the parent element */ }
呈现:
因此,堆栈上下文/顺序由z-index定义.但是当我应用z-index:1;到元素和z-index:-1;到它的::之前我不能实现同样的事情.
只有我从元素中省略了z-index.
任何想法为什么呢?这个元素是在它的:: before& ::伪造后,他们得到相同的z-index?
工作:https://jsfiddle.net/Ldtfpvxy/
不工作:https://jsfiddle.net/Ldtfpvxy/1/(仅添加z-index:1; to元素)
解决方法
您的div及其伪小孩是相同堆叠上下文的成员,在这种情况下是根堆栈上下文.给予伪元素的新堆叠上下文将被用作对其子节点(不存在)的引用,但z-index值适用于当前的堆叠上下文.而
CSS spec则为每个堆叠环境规定了以下油漆顺序:
Within each stacking context,the following layers are painted in
back-to-front order:
- the background and borders of the element forming the stacking context.
- the child stacking contexts with negative stack levels (most negative first).
- the in-flow,non-inline-level,non-positioned descendants.
- the non-positioned floats.
- the in-flow,inline-level,non-positioned descendants,including inline tables and inline blocks.
- the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
- the child stacking contexts with positive stack levels (least positive first).
看,具有负堆栈级别的子堆栈上下文,例如您的div ::之后在堆栈级别0的定位后代之前绘制,例如div本身.这解释了你注意到的行为.