What is use of box sizing in CSS
Here's a div
called Blue
:
div.Blue {
width: 100px;
height: 100px;
background-color: blue;
}
And here's a div
called Greenny
:
div.Greenny {
width: 100px;
height: 100px;
background-color: blue;
border: 20px solid green;
}
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:
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:
But if you want to add some padding
:
See what happened? Now I'll add box-sizing: border-box;
:
And now both div
s have width: 25%
again, but both also have padding: 10px
.
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.