Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I position an element on top of another while retaining document flow?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading