Search code examples
htmlcsscss-float

float:left changes the size of next div


I am practising on css box model.

this is the html and css code:

.box {
  width: 100px;
  height: 100px;
}

#first {
  background: red;
}

#second {
  background: blue;
}

#third {
  background: green;
}
<div class="box" id="first">box 1</div>
<p>
  Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quae nostrum aliquid, ullam delectus placeat quo, nam dignissimos minus eum hic ducimus sint commodi dolorum dolores eaque velit laboriosam ipsa perspiciatis.
</p>
<div class="box" id="second">box 2</div>
<div class="box" id="third">box 3</div>
this is how it looks like:

enter image description here

when I add float:left to the first box:

#first {
        background: red;
        float: left;
      }

why is the size of the second box is changing?

.box {
  width: 100px;
  height: 100px;
}

#first {
  float: left;
  background: red;
}

#second {
  background: blue;
}

#third {
  background: green;
}
<div class="box" id="first">box 1</div>
<p>
  Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quae nostrum aliquid, ullam delectus placeat quo, nam dignissimos minus eum hic ducimus sint commodi dolorum dolores eaque velit laboriosam ipsa perspiciatis.
</p>
<div class="box" id="second">box 2</div>
<div class="box" id="third">box 3</div>

enter image description here


Solution

  • Ok so any element that is not cleared will be moved to make space for the float, in the case of the boxes, this may be a bug but it's also because they are uncleared and they have nowhere to go, here is a fix by adding clear: both; to the .box class in css.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>...</title>
        <style>
          body {
            margin: 0;
          }
          .box {
            width: 100px;
            height: 100px;
            clear: both;
          }
    
          #first {
            background: red;
            float: left;
        
        }
          #second {
            background: blue;
          }
          #third {
            background: green;
          }
        </style>
      </head>
      <body>
        <div class="box" id="first">box 1</div>
        <p>
          Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quae nostrum
          aliquid, ullam delectus placeat quo, nam dignissimos minus eum hic ducimus
          sint commodi dolorum dolores eaque velit laboriosam ipsa perspiciatis.
        </p>
        <div class="box" id="second">box 2</div>
        <div class="box" id="third">box 3</div>
      </body>
    </html>