Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 213
jgoyon Avatar asked Apr 13 '13 15:04

jgoyon


1 Answers

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.

like image 161
BoltClock Avatar answered Nov 14 '22 01:11

BoltClock