Box Model

Every HTML element on a web page is a rectangular box and understanding how it is constructed is an important step towards exercising control over our websites. This is known as the box model.

The box model looks something like this:

We can change the size and behavior of each box by adjusting the width, height, padding, border, and margin of an element.

By setting a width and height value we can control the size of the content box. However, this does not account for the values for padding, border, and margin.

So, in order to calculate the total width of an element we would need to add the values for:

margin-right + border-right + padding-right + width + padding-left + border-left + margin-left

And for the total height of an element:

margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom

So, when we set the width and height values of an element, we are only setting the values for the content box and not for the total size of the element:


Box-Sizing

We are able to change how the total width and height of an element is calculated with the box-sizing property. By default, the box-sizing property is set to content-box. If we change the box-sizing property to border-box we can include the padding and border sizes in the total width and height of an element.

box-sizing: border-box;

This means that when we set the width and height properties of an element, they will always render at that exact width and height regardless of the padding and border sizes.

This is generally the preferred method of box sizing by most developers because it simplifies the calculation of the actual size of an element. When using border-box, the only thing left to be accounted for is the margin.

To make things easier we can add these lines to the top of our stylesheet to make every element render using border-box:

* { box-sizing: border-box; }

Typically, I add this to every stylesheet I’m working on.


Some other things to note regarding the box model and element sizing:


Further Reading