0

I have an example where I'm stacking a black div on top of a red div using position absolute. Then more content follows.

p {
  position: relative;
  z-index; 10
}

.wrapper {
  position: relative;
}

#red {
  height: 300px;
  width: 300px;
  background-color: red;
  position: absolute;
  z-index: 0;
}

#black {
  height: 200px;
  width: 200px;
  background-color: black;
  position: relative;
  z-index: 4;
}
<div class="wrapper">
  <p>Hello</p>
  <div id="red"></div>
  <div id="black"></div>
  <p>World</p>
</div>

How can I make it so World appears below the red div in flow with the rest of the DOM while retaining the stacked divs as they are.

Desired outcome: enter image description here The solution must use the regular DOM flow to achieve this. I.e. setting World to position: absolute and manually placing it in the right place is not what I want. Also preferably no JS used.

The crux of this issue is that I don't know how to stack elements without using position: absolute which takes the elements outside the DOM flow. But perhaps there is a better way to stack elements.

Mushroomator
  • 6,516
  • 1
  • 10
  • 27
Matt
  • 1,368
  • 1
  • 26
  • 54
  • Does this answer your question? [Using position:absolute while keeping it inside the document flow](https://stackoverflow.com/questions/18598031/using-positionabsolute-while-keeping-it-inside-the-document-flow) – ATP Aug 08 '23 at 15:22
  • It is but I think the answer below is cleaner than those answers – Matt Aug 08 '23 at 15:26

1 Answers1

1

I get the feeling this is too simple and may not be what you are looking for. But I got rid of all of the positioning and put the black square inside the red.

#red {
  height: 300px;
  width: 300px;
  background-color: red;
}

#black {
  height: 200px;
  width: 200px;
  background-color: black;
}
<div class="wrapper">
  <p>Hello</p>
  
  <div id="red">
    <div id="black"></div>
  </div>
  
  <p>World</p>
</div>
imvain2
  • 15,480
  • 1
  • 16
  • 21