Absolute positioned elements stack in opposite order (not as expected)

Viewed 60

#child_1, #child_2 {
  position: absolute;
  width: 100%;
  height: 100%;
  color: white;
}

#child_1 {
  background-color: green;
}

#child_2 {
  background-color: blue;
}
<div id="child_1">Green Child 1</div>
<div id="child_2">Blue Child 2</div>

Child 1 is positioned BEFORE Child 2 in the HTML. I therefore expect Child 1 to be displayed above Child 2, not the opposite way. Can someone explain what's going on?

Any help would be greatly appreciated!

1 Answers

Stacking without the z-index property

As you can read here and here, the order of absolutely positioned elements is determined as follows:

Without any z-index value, elements stack in the order that they appear in the DOM (the lowest one down at the same hierarchy level appears on top)

In your case, the lowest element in the DOM is #child_2, that's why it appears on top.

Use z-index for manual positioning

With this property, you can define a manual order on elements. An element with a higher z-index will be displayed above another with lower z-index.

Here's your modified snippet:

#child_1,
#child_2 {
  position: absolute;
  width: 100%;
  height: 100%;
  color: white;
}

#child_1 {
  z-index: 1;
}

#child_2 {
  z-index: 0;
}

#child_1 {
  background-color: green;
}

#child_2 {
  background-color: blue;
}
<div id="child_1">Green Child 1</div>
<div id="child_2">Blue Child 2</div>

Related