2

#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!

pppery
  • 3,731
  • 22
  • 33
  • 46
Chris
  • 1,597
  • 4
  • 18
  • 26
  • 1
    The child 2 is not positioned before child 1, first child 1 is positioned absolutely and the child 2 is there over the child 1 so the child 1 element is not visible (it is below child 2) – Ayush Jan 28 '22 at 11:44
  • 2
    why you think *before* and *above* goes together? it's more logical to have *before* and *below* together. When, in real life, you place elements the last one will be on the top – Temani Afif Jan 28 '22 at 11:46
  • 1
    Yes, in the same way like real life the last element goes above the first element like you keep one book on another book, the child2 goes above the child1 – Ayush Jan 28 '22 at 11:52
  • 1
    Re the edit, duplicate questions don't by default get deleted, but instead stick around as signposts exactly to allow others to locate the answer. – pppery Jan 30 '22 at 22:39

1 Answers1

1

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>
gru
  • 2,319
  • 6
  • 24
  • 39