Why is the red div in front of the green div when I remove z-index
from .wrapperRed
?
It feels like z-index
is inherited up the chain.
If I change the z-index
of the green div to 6, it stays in front of the red one even after removing 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>
The z-index of elements inside of a stacking context are always relative to the parent's current order in its own stacking context. The <html> element is a stacking context itself and nothing can ever go behind it. You can put stuff behind the <body> until you create a stacking context with it.
How to get a child element to show behind (lower z-index) than its parent? is to: Make the parent not a stacking context. Make the child a positioned stacking context , whose z-index smaller than 0.
the z-index default is auto which states "Sets the stack order equal to its parents". However, using z-index on the child will move it out of the natural stack order and place it behind the background.
The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.
When you remove z-index
from .wrapperRed
, the element defaults to 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
is auto
(reference).
Learn more about z-index
and stacking contexts here: Basics of the CSS z-index
property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With