What exactly is CSS box-sizing: border-box?

Have you ever wondered...

  • "What is border-box?"
  • "Should I be using it in my projects?"
  • "Should I use it just on my layout containers?... or everywhere?"

In short, box-sizing: border-box set on all elements in your projects will make your life infinitely easier.

But why, exactly?

Let's take a deeper dive into the CSS box model to find out.

The CSS Box Model is the defining visual design standard of all HTML elements on a web page.

Think of it as a series of wrapping rectangles surrounding an HTML element.

The innermost layer (blue in the image above) of the box model is called the content-box.

This is the layer immediately wrapping the text, or other nested child elements.

The next layer around the content-box is the padding-box. (green in the image above)

This layer allows you to create space between the content-box and the next layer, which is the border-box.

The final, outermost layer of the box model is the margin-box.

This is an area of empty space outside the border-box which allows for separation between sibling and parent elements.

So how does the box-sizing property fit into the overall box model?

By default, most browsers will give all elements the box-sizing property a value of content-box.

This means any height or width dimensions we give to an element will be attributed to the innermost layer of the box model, and any borders, padding, or margins we add will be in addition to those dimensions.

Here is where the default box-sizing: content-box tends to cause issues.

Say we have 50% width declared on an element, along with 20px of a border.

If we stick with box-sizing: content-box, this element's overall width dimensions will take up 50% + 40px (20px for each side) of space.

In reality, we want 50% to encompass the overall width of the element.

Declaring box-sizing: border-box allows us to do just that!


html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}