evaenrique evaenrique - 1 year ago 39
HTML Question

z-index inheriting to parent div?

Why is the red div in front of the green div when I remove


It feels like
is inherited up the chain.

If I change the
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 class="green"></div>

Answer Source

The elements .wrapperRed and .green are siblings. One is not the parent of another.

They will stack based on the value of their z-index property.

In your first case – where both elements have a z-index: 1 – the green div overlays the red one because the green div comes second in the source document (as per the cascade).

In your second case – where the second div has z-index: 6 – the green div overlays the red one because of the higher z-index value.

When you remove the z-index property 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 the z-index and stacking contexts here: Basics of the CSS z-index property

Answer edited based on feedback from @j08691 and @BoltClock (see comments).