Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

css - Why does z-index: -1; appear above z-index: 1;?

Explain this behavior:

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

http://jsfiddle.net/2VexH/2/

Only difference is the first div has z-index: 1 set.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...