Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the box-sizing property for in CSS?

Tags:

html

css

Is it necessary to specify a <div>s box-sizing?

What is it used for?

like image 271
Manohar Gunturu Avatar asked Aug 07 '15 14:08

Manohar Gunturu


2 Answers

Here's a div called Blue:

div.Blue {
      width: 100px;
      height: 100px;
      background-color: blue;
}

Blue

And here's a div called Greenny:

div.Greenny {
    width: 100px;
    height: 100px;
    background-color: blue;
    border: 20px solid green;
}

Greenny

Greenny is 40px wider and higher than Blue, so he decided to go on a diet:

div.GreennyAfterTheDiet {
    width: 100px;
    height: 100px;
    background-color: blue;
    border: 20px solid green;
    box-sizing: border-box;
}

Now his width and height are exactly 100px including borders:

Greenny after the diet

It's pretty simple, as you can see. The same rule works for padding.

UPDATE: Here's a simple use case:

<div>bla bla bla bla bla bla bla bla bla bla</div>
<div>bla bla bla bla bla bla bla bla bla bla</div>
<div>bla bla bla bla bla bla bla bla bla bla</div>
<div>bla bla bla bla bla bla bla bla bla bla</div>
div {
    width: 25%;
    float: left;
    background-color: #ffd862;
}

The result will look like this:

result

But if you want to add some padding:

after padding

See what happened? Now I'll add box-sizing: border-box;:

After box-sizing: border-box

And now both divs have width: 25% again, but both also have padding: 10px.

like image 74
Cheslab Avatar answered Oct 14 '22 17:10

Cheslab


The box-sizing property is used to tell the browser what the sizing properties (width and height) should include.

Here is an example:

Box 1 uses border-box, the whole box(including border) is 100px in width and height. Box 2 uses content-box, the whole box is 100px + (2x10)px border = 120px in width and height.

.box{
    width: 100px;
    height: 100px;
    background: deepskyblue;
    border: 10px solid #000;
}
.box.b1{
    box-sizing: border-box;
}
.box.b2{
    box-sizing: content-box;
}
<div class="box b1"></div><br/>
<div class="box b2"></div>

The box-sizing property can make building CSS layouts easier and a lot more intuitive as you don't have to keep track of the measurements as much.

like image 24
Starfish Avatar answered Oct 14 '22 16:10

Starfish