Box sizing model

Excerpt

Question: How to specify the size of a HTML Element in CSS ?

Answer: It depends.

There are 2 methods available:

content-box model

The content-box was created first and the calculation is given by

Total width = object width + padding left + padding right + border left + border right;
Total height = object height + padding top + padding bottom + border top + border bottom;

The problem with this model is that specifying the height is not actually specifying the height. I found it somehow un-normal. As an example when changing the border or padding style in a CSS rule you have to check all elements to adjust the width and height of the relevant elements.

border-box model

The border-box was created in about 2012 and was adopted in browsers since then and calculation is given by

Total width = object width;
Total height = object height;

Quite simple. The border and padding is included inside the the specified width and height.

Implementation

The box sizing model can be specified on each html element by using the box-sizing CSS attribute.

To set the box sizing model on a global level the following CSS can be used:

html {
  box-sizing: border-box;
}

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

This allows converting to the content-box model on a HTML container element in case you need to.

My Comments

Always border-box model ?

Not so fast. There is still some dependency and the content-box model is helpful when specifying text containing elements. Here is an example of a button implementation with such a problem:

<button style="height:1em;font-size:1em;line-height:1em">Click me</button>

When enforcing a specific height (or width) the available space for the text depends on the given border and padding. Using the content-box model on these elements is simplifying this inner-out requirement. When using a flex layout the outer-in model fits better.

Because the object margins are not included you still have the chance to get layout problems based on this and the border-box model is not helping here.

My (personal) preference and advice is to use the border-box model on all HTML elements used as controls like data input and output elements and the elements used next to them like buttons and labels.

Also pure formatting html elements like grids work better in this model.

On the other side there are elements that contain text content. You usually cannot predict their height especially in responsive design. Here I prefer the content-box model but avoid using borders.

But there are buttons...

See also

Tags

CSS