Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z-Index behaviour on pseudo elements

see:

http://jsfiddle.net/Kq2PY/

the div is relative with z-index 5, and the :after thing is absolute with z-index 2.

So shouldn't :after be behind the div?

div{
    position:relative;
    z-index: 5;
    background: #000;
    padding: 10px;
}    

div:after{
    content: '';
    position: absolute;
    z-index: 2;            /*  <= not working:( */
    background: #3d3;
    left: 20px;
    top: 20px; 
    width: 30px;
    height: 30px;
}    
<div>erferf</div>
like image 650
Alex Avatar asked Sep 17 '12 16:09

Alex


People also ask

Does Z Index working on pseudo element?

Pseudo-elements are treated as descendants of their associated element. That means by default (with no positioning, z-index or opacity applied) they sit above their parent in the stacking order.

How does an higher z index value affects an element?

The z-index property determines the stack level of an HTML element. The “stack level” refers to the element's position on the Z axis (as opposed to the X axis or Y axis). A higher value means the element will be closer to the top of the stacking order. This stacking order runs perpendicular to the display, or viewport.

Will Z Index work for an element without position?

z-index only works on positioned elements. If you try to set a z-index on a non-positioned element, it will do nothing. However, there is one exception - flex children can use z-index even if they're non-positioned.

What is the purpose of Z Index?

Z Index ( z-index ) is a CSS property that defines the order of overlapping HTML elements. Elements with a higher index will be placed on top of elements with a lower index. Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).


1 Answers

You would have to give pseudo elements a negative z-index to get it to go behind it's parent, plus remove the z-index on the parent. http://jsfiddle.net/jklm313/Kq2PY/4/

div{
    position:relative;
    background: #000;
    padding: 10px;
}    

div:after{
    content: '';
    position: absolute;
    z-index: -1;            /*  <= not working:( */
    background: #3d3;
    left: 20px;
    top: 20px; 
    width: 30px;
    height: 30px;
}    
<div>erferf</div>
like image 51
carpenumidium Avatar answered Sep 19 '22 10:09

carpenumidium