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 solidrenders 244px wide undercontent-boxand 200px underborder-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-rootor padding on the parent. - Clicks register on padding, not on margin.
Related
- 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.