为什么z-index:-1;出现在z-index之上:1 ;? [英] Why does z-index: -1; appear above z-index: 1;?
问题描述
解释此行为:
<div style="z-index: 1"></div>
<div></div>
<div></div>
<div></div>
div {
position: relative;
background: red;
width: 100px;
height: 100px;
}
div:before {
position: absolute;
background: blue;
width: 100px;
height: 100px;
z-index: -1;
content: "";
left: -5px;
top: -5px;
}
只有区别是第一个div有z-index:1 set。 p>
Only difference is the first div has z-index: 1 set.
推荐答案
设置定位元素 z-index
到 auto
(初始值)
Setting a positioned element's z-index
to anything other than auto
(the initial value) causes the element to generate a new stacking context for its descendant boxes.
这会阻止它的任何后代出现在它的下面,包括 div:before
伪元素,即使它们的 z-index
是负的。当然,具有负值 z-index
的任何后代将继续出现在具有零或正值 z-index $ c $ <>
This prevents any of its descendants from appearing below it, including the div:before
pseudo-element, even if their z-index
is negative. Of course, any descendant with a negative z-index
will continue to appear below a descendant with a zero or positive z-index
within the containing element, but that containing element will always be at the very back.1
您的<$ c $的其余部分没有 z-index
集合的c> div 元素将使用初始值,因此不会为其伪元素,允许伪元素出现在真实元素下面。它们的堆叠上下文是 body
的堆叠上下文。
The rest of your div
elements that don't have a z-index
set will use the initial value instead, and therefore not generate stacking contexts for their pseudo-elements, allowing the pseudo-elements to appear below the real elements. The stacking context in which they are drawn instead is that of body
.
1 请注意,堆叠上下文根目录的内容仍会显示在后代的背景 code> z-index 。这是有意的,详情请参阅此答案,其中包含规范的相关链接。
1 Note that the content of a stacking context root will still appear above the background of a descendant with a negative z-index
. This is intentional, and is covered in greater detail in this answer, with relevant links to the spec.
这篇关于为什么z-index:-1;出现在z-index之上:1 ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!