box-sizing border-box Makes width Include Padding and Border

In progress

Every element is laid out as nested boxes: content, then padding, then border, then margin. By default (box-sizing: content-box), width and height size only the content, and padding and border are added on top: a width: 300px box with 10px padding and a 1px border takes 322px. With box-sizing: border-box, width is the outer size of the border box and the content shrinks to fit, which is what people usually mean by "300 pixels wide".

The Two Models

content-box (default) border-box
width applies to the content only content + padding + border
Rendered width of width: 300px; padding: 10px; border: 1px 322px 300px (content 278px)
Margin outside, in both models outside, in both models

Most projects switch every element to border-box, inheriting so components can opt out:

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

Tailwind's base styles (Preflight) already set border-box on everything.

Negative Margins to Escape a Parent's Padding

A child can extend past its container's padding, for a full-bleed image or banner, with equal negative horizontal margins and a width that adds back what they remove:

/* parent padding totals 2.5rem per side; keep a 10px gutter */
.full-bleed-child {
  width: calc(100% + 5rem - 20px);
  margin-left: calc(-2.5rem + 10px);
  margin-right: calc(-2.5rem + 10px);
  box-sizing: border-box;
}

References

Review cards

Flashcard How wide does width: 300px; padding: 10px; border: 1px render in content-box and in border-box?

322px in content-box, where padding and border are added to the width. 300px in border-box, where the content shrinks to 278px.

Quiz Which of the following CSS rules will ensure that all elements in a project use `border-box` for their box-sizing?
  • html { box-sizing: content-box; } * { box-sizing: inherit; }
  • html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; }
  • html { box-sizing: border-box; } * { box-sizing: content-box; }
  • html { box-sizing: content-box; } *, *::before, *::after { box-sizing: border-box; }

The correct rule sets html to border-box and inherits border-box for all descendants.