amith.gotamey
amith.gotamey

Reputation: 988

CSS Absolute Positioning & Z-Index

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!

Upvotes: 1

Views: 7124

Answers (2)

Jorden
Jorden

Reputation: 163

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>

Upvotes: 2

Michael Benjamin
Michael Benjamin

Reputation: 371271

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>

Upvotes: 1

Related Questions