2

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

Kareem Dabbeet
  • 3,838
  • 3
  • 16
  • 34
Sinan
  • 33
  • 1
  • 1
  • 8
  • 1
    if you practise, then learn not to mis-use `float`. `float` is for floating images within a text-block. It is not intended to be used for styling purpose. Unfortunatly this hack is still tought at sites like w3school. For modern web devlopment (since 2015) you should use flexbox or css-grid instead! – tacoshy Oct 16 '21 at 18:16

1 Answers1

3

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>
FurrySenko
  • 549
  • 3
  • 12