htmlcssmargin

Html <div> leaves unexpected margins


I am new to HTML and CSS. I was experimenting with displaying <div> -s side by side. I noticed that simply adding a div inside the body will display with unexpected margins.

I tried messing about with margin, border and padding properties in my css file but nothing seems to work. the div leaves a gap to every side of the page, please help, I don't know how to get rid of it.

The HTML:

* {
  box-sizing: border-box;
}

.box {
  float: left;
  width: 50%;
}

#box1 {
  background-color: grey;
}

#box2 {
  background-color: lightblue;
}

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="clearfix">
    <div id="box1" class="box">
      <p>Some text in box 1.</p>
    </div>

    <div id="box2" class="box">
      <p>Some text in box 1.</p>
    </div>
  </div>
</body>

</html>


Solution

  • Another option would be to set the box positions to absolute (as in this answer)

    * {
      box-sizing: border-box;
    }
    
    .box {
      float: left;
      width: 50%;
    }
    
    #box1 {
      background-color: grey;
      position: absolute;
      left: 0px;
      top: 0px;
    }
    
    #box2 {
      background-color: lightblue;
      position: absolute;
      left: 50%;
      top: 0px;
    }
    
    .clearfix::after {
      content: "";
      clear: both;
      display: table;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <link rel="stylesheet" href="styles.css">
    </head>
    
    <body>
      <div class="clearfix">
        <div id="box1" class="box">
          <p>Some text in box 1.</p>
        </div>
    
        <div id="box2" class="box">
          <p>Some text in box 1.</p>
        </div>
      </div>
    </body>
    
    </html>