Quiz

What does `* { box-sizing: border-box; }` do?

What are its advantages?
Topics
CSS

TL;DR

* { box-sizing: border-box; } makes every element selected by * include its padding and border within its declared width and height; margins remain outside. This prevents padding from unexpectedly increasing a percentage-sized box. The selector does not include pseudo-elements, so a project-wide rule commonly includes *::before and *::after or uses inheritance from html.


What does * { box-sizing: border-box; } do?

How the calculation changes

The initial content-box value applies a declared size to the content box. Padding and borders are added outside it. With border-box, the declared size describes the border box and the content area shrinks to make room for padding and borders.

.field {
box-sizing: border-box;
width: 100%;
padding: 0.75rem;
border: 2px solid;
}

Here, the field's border box remains 100% wide. With content-box, its border box would be 100% plus the inline padding and borders, which can overflow its container.

For a 100px width with 10px of padding and a 5px border on each side:

ValueContent widthBorder-box width
content-box100px130px
border-box70px100px

Margins are not included in either width.

A project-wide convention

The literal universal rule applies to elements but not their ::before and ::after pseudo-elements. One common reset is:

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

Using inheritance makes a subtree easier to opt back into content-box if an embedded widget depends on that model. A direct border-box declaration on all three selectors is also valid.

Advantages and limits

border-box makes component and grid sizing easier to calculate, particularly when percentages, padding, and borders are combined. It does not guarantee that an element fits: margins, intrinsic minimum sizes, long unbreakable content, min-width, transforms, and overflowing descendants can still extend beyond the container.

Switching an established application globally can break components written around content-box, especially third-party widgets. Introduce the convention early or test the migration. Use content-box deliberately when the content area itself must retain the exact declared dimensions.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise 1 of 2
Check your understanding Exercise 1 of 2

Which statements about box-sizing: border-box are correct? Select all that apply.