Why 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; } The only difference is that the first div has z-index: 1 set.
Setting the z-index positional element to anything other than auto (initial value) causes the element to generate a new contextualization context for its descendants.
This prevents any of its descendants from appearing, including the div:before pseudo-element, even if their z-index negative. Of course, any descendant with a negative z-index will still appear below a descendant with a zero or positive z-index inside the containing element, but this containing element will always be at the very end. one
The rest of the div elements that do not have the z-index set will instead use the initial value and therefore will not create stacking contexts for their pseudo-elements, allowing the pseudo-elements to appear under the real elements. The stacking context in which they are drawn is as follows: body .
1 Note that the contents of the stack context root will still be displayed above the background of the child with a negative z-index . This is intentionally and discussed in more detail in this answer with appropriate references to the specification.