Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z-index on sibling absolute elements

I'm trying to grasp why the blue divs in this example are not always on top? i.e. how come red div #2 is on top of blue child 1.

body {
  padding: 30px;
}
.red1 {
  position: absolute;
  z-index: 1;
  width: 400px;
  height: 200px;
  background: red;
}
.red2 {
  position: absolute;
  z-index: 1;
  width: 400px;
  height: 200px;
  top: 250px;
  background: red;
}
.blue {
  z-index: 9;
  padding: 10px;
  text-align: center;
  color: white;
  text-transform: uppercase;
  position: absolute;
  top: 100px;
  left: 100px;
  width: 150px;
  height: 130px;
  background: blue;
}
<div class="red1">
  <div class="blue">
    blue child 1
  </div>
</div>
<div class="red2">
  <div class="blue">
    blue child 2
  </div>
</div>

FIDDLE

like image 442
Kirk Ross Avatar asked Jul 26 '16 17:07

Kirk Ross


People also ask

Does Z-Index work with absolute?

Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

Is Z-Index absolute or relative?

z-index is relative.

What happens if two elements have the same z-index?

If several elements share the same z-index value (i.e., they are placed on the same layer), stacking rules explained in the section Stacking without the z-index property apply.

Can we use Z-index without absolute?

Yes: use position:relative; z-index:10 . z-index has no effect for position:static (the default).


2 Answers

Because .red1 and .red2 form different stacking contexts.

The elements within one stacking context do not participate along with the elements within another stacking context.

If you give .red2 a z-index: -1, you will get the behavior you expect (demo).

That's because .red1 and .red2 are both absolutely positioned with no positioned ancestor. This means the root element is their immediate ancestor, and the root element forms a stacking context.

More details here:

  • Basics of the CSS z-index property
  • Understanding z-index: How does this element appear in front of its parent's sibling?
like image 151
Michael Benjamin Avatar answered Sep 29 '22 07:09

Michael Benjamin


body {
  padding: 30px;
}
.red1 {
  position: absolute;
  z-index: 1;
  width: 400px;
  height: 200px;
  background: red;
}
.red2 {
  position: absolute;
  z-index: 1;
  width: 400px;
  height: 200px;
  top: 250px;
  background: red;
}
.blue {
  z-index: 9;
  padding: 10px;
  text-align: center;
  color: white;
  text-transform: uppercase;
  position: absolute;
  top: 100px;
  left: 100px;
  width: 150px;
  height: 130px;
  background: blue;
}
<div class="red2">
  <div class="blue">
    blue child 2
  </div>
</div>
<div class="red1">
  <div class="blue">
    blue child 1
  </div>
</div>
like image 21
Louai Drissi Avatar answered Sep 29 '22 06:09

Louai Drissi