Search code examples
htmlcsscss-calc

Adding margin to div pushes it off the screen


I would like to have a 5px margin around each of my divs but when I add it in CSS, there is a 5px margin on every side except for in between the divs and on the bottom. The two divs also overflow off the page on the bottom. I understand this is because of the 5px margin on top pushing the divs off screen. I am unsure how to make it just add the margin all around and shrink the divs accordingly.

* {
  box-sizing: border-box;
  margin: 0;
}

html {
  width: 100%;
  height: 100%;
}

body {
  background: black;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.one {
  background: red;
  position: absolute;
  width: 10%;
  height: 100%;
  left: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}

.two {
  background: blue;
  position: absolute;
  width: 90%;
  height: 100%;
  right: 0;
  border: 3px solid green;
  border-radius: 5px;
  margin: 5px;
}
<div class="one">
</div>
<div class="two">
</div>

Resulting Page

Divs pushed off screen on bottom and no margin in-between divs. 5px margin on top, left, and right is present.

resulting page

I am new to HTML and CSS so any helps greatly appreciated.


Solution

  • Use CSS Flex

    /*QuickReset*/ * { box-sizing: border-box; margin: 0; }
    
    html {
      height: 100%;
    }
    
    body {
      background: black;
      height: 100%;
      position: relative;
      
      display: flex; /* Use flex! */
      padding: 5px; /* Instead of children margin */
      /* gap: 5px; /* Uncomment to add a gap between your child elements! */
    }
    
    .one,
    .two {
      border: 3px solid green;
      border-radius: 5px;
    }
    
    .one { width: 10%; background: red;  }
    .two { width: 90%; background: blue; }
    <div class="one">
    </div>
    <div class="two">
    </div>