Effect of the z-index of an element on the z-index: before /: after a pseudo-element

Here is a behavior that I don’t quite understand regarding the z-index and css of the :: before / :: after pseudo-element.

This is illustrated on this jsfiddle: http://jsfiddle.net/jgoyon/T6QCf/

I created a placed box and added the contents with :: after the pseudo-element (also positioned).

  • if I set the z-index for the after after element, everything works fine, and I can position it above the parent or under the parent, playing with z-index
#no-z-index { background:lightblue; width:100px; height:100px; position:relative; } #no-z-index:after { content: 'z-index -1'; width:50px; height:50px; background:yellow; position:absolute; z-index:-1; /* z-index in question */ top:70px; left:70px; } 
  • If I do the same and set the z-index of the parent, it no longer works.
  #z-index { background:lightblue; left:200px; width:100px; height:100px; position:relative; z-index:0; /* parent z-index */ } #z-index:after { content: 'z-index -1'; width:50px; height:50px; background:yellow; position:absolute; z-index:-1; /* z-index in question */ top:70px; left:70px; } 

Is this expected behavior?

+6
source share
1 answer

This is the expected behavior described in spec .

If you do not specify a z-index for the generating element ( auto by default), the generating element and pseudo element will be displayed in the same stacking context. This allows the pseudo-element to appear below the element if its z-index lower.

When you specify a z-index on a generating element, this element creates a new stacking context for the pseudo-element (and virtually all of its descendants), preventing the pseudo-element from appearing under it, even if you give it a negative z-index .

+10
source

All Articles