1

Say I have the following HTML:

.wrapper {
  position: relative;
  z-index: 99;
}

.red, .green {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
}

.red {
  background: red;
  z-index: 400;
}

.green {
  background: green;
}
<div class="wrapper">
  <div class="red"></div>
</div>
<br>
<div class="wrapper">
  <div class="green"></div>
</div>

I would like the red box to appear on top of the green box. But it doesn't. The .wrapper has z-index of only 99 whereas .red has z-index: 100. Are there any hacks top produce .red on top?

Thanks in advance!

amith.gotamey
  • 968
  • 8
  • 14

2 Answers2

2

You don't want to give the wrapper thats containing both of those divs a z-index because it's containing both of those divs. Get rid of the z-index on the .wrapper. and leave the .red class a z-index of 400 and the red box will appear on top of the green one:

.wrapper {
  position: relative;
}

.red, .green {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
}

.red {
  background: red;
  z-index: 400;
}

.green {
  background: green;
}
<div class="wrapper">
  <div class="red"></div>
</div>
<br>
<div class="wrapper">
  <div class="green"></div>
</div>
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Jorden
  • 153
  • 1
  • 3
  • 16
1

You're setting both containers to z-index: 99. Therefore, since the z-index is the same for both, source order decides placement on the z-axis.

The .wrapper element with the green div comes last in your code, so it prevails. (Switch the order of the .wrapper elements, and the red wins out.)

The z-index: 400 on the red child is having no effect since the stacking order that matters is that of the containers.

Try this:

.wrapper:first-child {
  position: relative;
  z-index: 2;
}
.wrapper:last-child {
  position: relative;
  z-index: 1;
}
.red, .green {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
}

.red {
  background: red;
}

.green {
  background: green;
}
<div class="wrapper">
  <div class="red"></div>
</div>
<br>
<div class="wrapper">
  <div class="green"></div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • What if those `.wrapper` divs were auto-generated and I did not have the count or the order beforehand? – amith.gotamey Jun 17 '17 at 05:56
  • Can you post a more detailed example? Also, read the post linked to in my answer. It may answer your question. – Michael Benjamin Jun 18 '17 at 11:34
  • 1
    I was trying to make a custom Select2 component, and the dropdown z-index was messed up. Anyway, thanks for the answers, I'm reverting back to other libraries. – amith.gotamey Jun 22 '17 at 10:24