How can I stop divs from overlapping?

Viewed 60

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?

3 Answers

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.

Your immediate problem has been solved - as others have suggested you can set box-sizing so the padding is included in the dimensions.

However, your HTML is quite complex because of using flex. Your desired layout looks more like a grid - grid being suited to 2D type layouts.

This snippet simplifies your HTML - each of the elements is at the same 'level' the need for separate sections being removed.

The grid-template-areas CSS property is used to layout the contents.

* {
  box-sizing: border-box;
}

body {
  background-color: #D3D3D3;
}

#container {
  display: grid;
  grid-template-columns: 1fr 9fr;
  grid-template-areas: 'H H' 'C1 C3' 'C2 C3' 'F F';
  width: 100%;
  gap: 10px;
  padding: 20px;
}

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

.header {
  grid-area: H;
}

.content1 {
  grid-area: C1;
}

.content2 {
  grid-area: C2;
}

.content3 {
  grid-area: C3;
}

.footer {
  grid-area: F;
}
<div id="container">
  <div class="header show"> header </div>
  <div class="content1 show"> content 1</div>
  <div class="content2 show"> content 2</div>
  <div class="content3 show"> content 3</div>
  <div class="footer show"> footer</div>
</div>

Related