What is the box-sizing property for in CSS?

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.

Leave a Comment