CSS Box-sizing

In the previous article that covers CSS subjects, we talked about the box model. An important property that’s connected to the box model is the box-sizing property.

CSS Box-sizing

In the previous article that covers CSS subjects, we talked about the box model. An important property that’s connected to the box model is the box-sizing property.

The box-sizing property defines how the height and width of the element are calculated and if it should include the border, padding and margin or not.

Values

There are two possible values for the box-sizing property:

  • Content-box - the default value.
  • Border-box.

Let's see how the width is calculated in both cases.

For a reminder, the box model looks like this:

box_7-1

Content-box

The default value of the box-sizing property is content-box. We will explain how the width is calculated in this case.

Even though we set the width of our element to 200px, the actual width will be much different. The formula is:

Width = left margin + left border + left padding + content + right padding + right border + right margin

So in the case of our example the width would be:

Width = 20px + 3px + 10px + 200px + 10px + 3px + 20px

The result of this calculation is 266px. This is probably not the result you expected, am I right? That’s why you need to really be careful about this.

Now, you’re probably wondering if there is an easier way to deal with width, than having to use the calculator every time? There is! By using a border-box.

Border-box

Let’s take our example. We specified the width of the element to be 200px, and the padding is 10px on each side. If we were to use content-box, then it’s becoming 220px.

But, when using border-box, the width will be 200px, which means the width of the content will be 180px and the padding is 20px. The content shrinks in size, to accommodate the addition of padding.

Example

Let’s see a visual example of both situations to better explain the properties.

HTML

<div class=”content-box”>Content-box</div>
<div class=”border-box”>Border-box</div>

CSS

div {
  height: 200px;
  width: 200px;
  background-color: hotpink;
  color: #fff;
  padding: 10px;
  border: solid 3px black;
  margin: 20px;
}

.content-box {
  box-sizing: content-box
}

.border-box {
  box-sizing: border-box;
}

content

As we see, in the first example, the width of the content-box adds up to 266px, while the border-box adds up to 200px.

Conclusion

We have seen the connection between the box-sizing property and the box model, and it is an important one. It is of great value to understand both the content-box and border-box value of the box-sizing property. While the content-box is the default value, it is much easier to use the border-box property to avoid calculations which are often confusing.

Happy coding!