Overview

The box model renders every element as four nested areas: content, padding, border, and margin. By default (box-sizing: content-box) width and height size only the content, so adding padding to a fixed width makes the element overflow its container, the cause of most misaligned-width bugs. Set box-sizing: border-box globally so width includes padding and border.

Rules

Reset sizing once at the top of every stylesheet:

*, *::before, *::after { box-sizing: border-box; }
  • width: 200px; padding: 20px; border: 2px solid renders 244px wide under content-box and 200px under border-box.
  • Vertical margins of adjacent blocks collapse (the larger wins), also between a parent and its first or last child when no border or padding separates them. Flex and grid items do not collapse. Break collapsing with display: flow-root or padding on the parent.
  • Clicks register on padding, not on margin.
  • css: layout rules built on the box model.
  • css-flexbox: flex items do not collapse margins.
  • em-vs-rem: relative units interact with box sizing.
  • viewport: the outer frame that block widths resolve against.
  • cls: unreserved box sizes cause cumulative layout shift.