Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About float in CSS

Tags:

css

css-float

I'm having some troubles with the 'float' in css. I have a wrapper div with a width of 960px.I want to add 5 child-div in it with the width of 960 / 5 = 192px. And this is what I've got: https://i.sstatic.net/R6bsw.png

This is my lines of code. Can anyone tell me what's wrong with them?

HTML

#overall-info h1 {
  text-align: center;
  padding: 1em;
}

.box {
  width: 192px;
  height: 192px;
  border: 1px solid green;
  background-color: aquamarine;
  float: left;
}
<section id="overall-info">
  <div class="container">
    <h1>Info</h1>
    <div class="box">

    </div>

    <div class="box">

    </div>

    <div class="box">

    </div>

    <div class="box">

    </div>

    <div class="box">

    </div>
  </div>
</section>
like image 371
DunDev Avatar asked Mar 22 '26 00:03

DunDev


2 Answers

For each sub-boxes you have 1px of border which successively adds up to the total width.

So the container should have a width of (192+1+1)*5 = 970 and not 960 if you want all your sub-boxes to be contained on one line. You can also suppress the border or use a sub-box width of 190 (190+1+1=192)

Furthermore keeping 1px of free width space for the container can also help

About box-sizing:border-box:

The width and height properties (and min/max properties) includes content, padding and border, but not the margin.

For Fix it:

So, you must use box-sizing:border-box; because width of .box(192px) includes .box border width (1px for border-left and 1px for border-right).

if you don't add box-sizing:border-box,it will be added 2px(1px for border-left and 1px for border-right) to each .box,in the other words width .box gets width (192px + 2px = 194px).

* {
  box-sizing:border-box;
}

* {
    box-sizing: border-box;
}

.container {
    width: 960px;
}


#overall-info h1 {
    text-align: center;
    padding: 1em;
}

.box {
    width: 192px;
    height: 192px;
    border: 1px solid green;
    background-color: aquamarine;
    float: left;
}
<section id="overall-info">
    <div class="container">
        <h1>Info</h1>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
    </div>
</section>
like image 37
Ehsan Avatar answered Mar 23 '26 19:03

Ehsan