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 stop divs from overlapping?

Here’s the fiddle:

body {
  background-color: #D3D3D3;
}

#container {
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 10px;
  padding: 20px;
}

.section1 {
  display: flex;
  justify-content: center;
}

.section2 {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.column {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.show {
  padding: 20px;
  border: 2px black solid;
  width: 100%;
}

.section3 {
  display: flex;
  justify-content: center;
}
<div id="container">

  <div class="section1">
    <div class="header show"> header </div>
  </div>

  <div class="section2">
    <div class="column">
      <div class="content1 show"> content 1</div>
      <div class="content2 show"> content 2</div>
    </div>
    <div class="content3 show"> content 3</div>
  </div>

  <div class="section3">
    <div class="footer show"> footer</div>
  </div>

</div>

I tried using overflow: auto;, overflow: hidden;, and z-index: 1; but all of those didn’t work. I this has something to do with the width: 100%; in the .show divs. I tried using width: 60%; instead and that stops it from overlapping but it doesn’t occupy all the width. What should I do to stop the .show divs from overlapping while maintaining all the width?

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

>Solution :

If you use box-sizing: border-box that will solve your issues: the reason being that when you have padding: 20px; width: 100%, it actually adds 40px to the already 100% width, unless you explicitly set this box-sizing property.

* {
  box-sizing: border-box;
}

This will fix your layout issues: see proof-of-concept fix of your fiddle. This is also why it’s recommended to use a CSS reset.

p/s: Consider using CSS grid for your layout, it’s way easier to reason about.

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