Daniel Tea


The box-sizing property is used to tell the browser how to calculate the width and height of an element. By default, this is set to content-box, which may cause some unexpected behavior for someone new to CSS.

content-box tells the browser:

  • to calculate displayed height: use height + padding + border
  • to calculate displayed width: use width + padding + border

So, if you set height: 20px, you're telling the browser that you want the content to have a height of 20px. It does not mean that it will get displayed at 20px. This can cause some issues with layout, especially if you have some fixed dimension containers. You could probably get by with calculating the correct height and width for your element manually, but who wants to do that?

Enter: border-box

border-box is a way to tell the browser that when you set height: 20px, you want the rendered height to be 20px.

In this example, both divs contain similar styles.

div {
  width: 200px;
  height: 200px;

  margin: 20px;
  padding: 10px;
  border: 5px solid #ffe66d;
}

The difference is, the one on the left has box-sizing: content-box; and the one on the right has box-sizing: border-box. The CSS markup is telling the divs to have a height of 200px and a width of 200px. However, because of the box-sizing difference, they get rendered differently. The content-box gets rendered with 230px (200 + 10 + 10 + 5 + 5), while the border-box makes the content area smaller to account for a total width and height of 200px. My suggestion is to use border-box for a more intuitive behavior and avoid unnecessary cognitive load to account for borders and paddings when using content-box.

References