Boxes and positioning

Box sizing

Compare content-box with border-box and make declared widths include padding and borders for predictable component sizing.

6 minute lesson

~~~

With the default content-box, a declared width applies only to content. Padding and border are added outside it.

A 200px box with 20px padding and 5px borders occupies 250px horizontally.

border-box includes padding and border inside the declared dimensions:

html {
  box-sizing: border-box;
}

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

This common rule makes component dimensions easier to reason about and lets a component deliberately choose another model that descendants inherit. Margin remains outside the declared width.

With border-box, the browser subtracts padding and borders to find the content box. If those layers consume more than the declared size, the content box cannot become negative; the element still needs enough border and padding space.

box-sizing does not stop content from overflowing a box that is too small. You still need flexible dimensions, wrapping, or overflow handling.

Create two otherwise identical inputs at width: 100%, give them padding and borders, and toggle content-box versus border-box in DevTools. Measure the containing block and border box instead of relying on visual alignment.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →