Search code examples
htmlcssz-indexstacked

Z-indexes: Two stacked divs, both with pseudo:before that have to be behind their respective element. Not possible?


http://jsfiddle.net/qzLykrba/1/

Red box is the parent div. Blue box is the child div. Purple box is the parent pseudo:before, that has to be behind the parent red box. Green box is the child pseudo:before, that has to be behind the child blue box, but above the parent red box.

I can't get the parent pseudo element behind the parent div. I know that I have to remove the parent z-index to get the parent pseudo element behind the parent, but if I do, then the childs pseudo element goes behind the parent div too.

.parent { 
width: 400px;
height: 400px;
background-color: red;
position: relative;

margin-left: 50px;
}

.parent:before { 
z-index: -1;
position: absolute; 
content: ""; 
bottom: -50px; 
left: -30px; 
width: 100px; 
height: 100px; 
background: purple; 
}

.child { 
width: 400px;
height: 100px;
background-color: blue;
position: relative;
top: 50px;
}

.child:before { 
z-index: -1;
position: absolute; 
content: ""; 
bottom: -50px; 
left: -30px; 
width: 100px; 
height: 100px; 
background: green; 
}

Solution

  • Unfortunately that is not possible, since the pseudo elements act like children of the element they are assigned to.

    <div class="parent">    z: 5
       :before              z: 4 // still above the parent, since it's a child of it
       <div class="child">  z: 3 // below parent:before, above parent
           :before          z: 2 // above child
           "Some text"      
           :after           z: 1 // below child:before, above child
        </div>              
       :after               z: 2 // below child, parent:before
    </div>
    

    Another note:

    Negative values for z-indexes are not overall supported, or don't produce the same behavior.