1

I try to get familiar with the different positioning attributes and the z-index. While playing around I noticed that child elements are covering the parent element even if the parent has a z-index of 1:

div {
  width: 200px;
  height: 200px;
}

.red {
  background-color: red;
  position: absolute;
}

.blue {
  background-color: blue;
  position: absolute;
  left: 1877px;
}

.yellow {
  background-color: yellow;
}

.white {
  background-color: white;
  position: absolute;
  left: 650px;
  z-index: 1;
}
<div class="white">
  <div class="red"></div>
</div>
<div class="blue"></div>
<div class="yellow"></div>

So the div element with the class "white" is covered by the "red" div despite a z-index of 1... Could anyone please explain me the behavior?

j08691
  • 204,283
  • 31
  • 260
  • 272
Dawienchi
  • 75
  • 1
  • 9
  • Read about z-index and stacking context here https://developer.mozilla.org/en-US/docs/Web/CSS/z-index – j08691 Jun 21 '22 at 20:07
  • try to add a different z-index in every class with a smaller left:10px, 20px 30px in each, and play with it, you will get it easier – BenoHiT Jun 21 '22 at 20:12

1 Answers1

1

The white div has z-index: 1;, sure, but this just means this div and it's content will be on top. As your red div is also part of the content of the white div, nothing has changed.

EXAMPLE
If you give the red div the same position as the white one, then put it outside of the white div, you will get the result you expected.

div {
  width: 200px;
  height: 200px;
}

.red {
  background-color: red;
  left: 650px;
  position: absolute;
}

.blue {
  background-color: blue;
  position: absolute;
  left: 1877px;
}

.yellow {
  background-color: yellow;
}

.white {
  background-color: white;
  position: absolute;
  left: 650px;
  z-index: 1;
}
<div class="white"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="yellow"></div>

If you remove your white div's z-index, you will see the red div again:

div {
  width: 200px;
  height: 200px;
}

.red {
  background-color: red;
  left: 650px;
  position: absolute;
}

.blue {
  background-color: blue;
  position: absolute;
  left: 1877px;
}

.yellow {
  background-color: yellow;
}

.white {
  background-color: white;
  position: absolute;
  left: 650px;
}
<div class="white"></div>
<div class="red"></div>
<div class="blue"></div>
<div class="yellow"></div>

CONCLUSION
The z-index applies to the element and it's child elements.

Camelopardalus
  • 499
  • 1
  • 4
  • 20