7

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

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

I created a positioned box and added content with ::after pseudo element (positioned as well).

  • if I set a z-index to the ::after pseudo element, everything is working well and I can position it over or under the parent by 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 doesn't work anymore.
    #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 it an expected behavior ?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
jgoyon
  • 139
  • 8

1 Answers1

11

This is expected behavior, documented in the spec.

When you don't specify z-index on the generating element (defaulting to auto), the generating element and the pseudo-element will appear in the same stacking context. This allows the pseudo-element to appear below the element if its z-index is lower.

When you do specify z-index on the generating element, that element creates a new stacking context for the pseudo-element (and in fact all of its descendants), preventing the pseudo-element from ever appearing below it even if you give it a negative z-index.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • And I just remembered [answering a duplicate question](http://stackoverflow.com/questions/11712040/why-does-z-index-1-appear-above-z-index-1/11712096#11712096) some time back. – BoltClock Apr 13 '13 at 15:34