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

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:

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

* {
  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>
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