Understanding z-index: how does this element appear in front of the parent sibling?

Why is the red div in front of the green div when I remove the z-index from .wrapperRed ?

It looks like the z-index inherited before the chain.

If I change the z-index green div to 6, it will remain in front of red even after deleting the line described in the first sentence.

 .wrapperRed { height: 200px; width: 200px; position: absolute; z-index: 1; /* Why is the red div in front of the green one, if this z-index is deleted? */ } .red { position: absolute; height: 100%; width: 100%; background-color: red; z-index: 5; } .green { height: 200px; width: 200px; background-color: green; position: absolute; top: 100px; left: 100px; z-index: 1; } 
 <div class="wrapperRed"> <div class="red"></div> </div> <div class="green"></div> 
+7
html css z-index
source share
2 answers

When you remove z-index from .wrapperRed , the default is z-index: auto .

In this case, both .red and .green participate in the same stacking context, because positioned elements do not create a stacking context when z-index auto ( link ).

Read more about z-index and the stacking context here: Basics of the z-index CSS Property

+2
source share

Why is div.red in front of the green div when I remove the z-index from .wrapperRed?

Since .red no longer has a parent z-index to restrict it.

e.

Before: .red has a z-index of 5 in the parent z-index of 1.

After: .red has a global z-index of 5.

NB In both cases, before and after .wrapperRed always behind .green . But, when it is not bound, .green appears before .green (which is 100% width and height .wrapperRed ).


You can see this more easily if you give the parent and child divs different background colors and make the child div smaller than the parent.

For comparison:

 .wrapperRed { height: 200px; width: 200px; position: absolute; background-color: red; z-index: 1; } .yellow { position: absolute; height: 75%; width: 75%; background-color: yellow; z-index: 5; } .green { height: 200px; width: 200px; background-color: green; position: absolute; top: 100px; left: 100px; z-index: 1; } 
 <div class="wrapperRed"> <div class="yellow"> </div> </div> <div class="green"></div> 

from:

 .wrapperRed { height: 200px; width: 200px; position: absolute; background-color: red; } .yellow { position: absolute; height: 75%; width: 75%; background-color: yellow; z-index: 5; } .green { height: 200px; width: 200px; background-color: green; position: absolute; top: 100px; left: 100px; z-index: 1; } 
 <div class="wrapperRed"> <div class="yellow"> </div> </div> <div class="green"></div> 
+1
source share

All Articles