Everything is a box
Every element is a rectangle with four layers: the content, padding around it, a border, and margin outside. This is the box model, and it explains almost every spacing puzzle.
The four layers
- Shorthand: padding: 8px 16px = top/bottom 8, left/right 16. Four values go clockwise: top, right, bottom, left.
- box-sizing: border-box makes width include padding and border — far easier. Most sites set it on everything with * { box-sizing: border-box; }.
- Vertical margins between blocks collapse: two 12px margins make a 12px gap, not 24px.
- margin: 0 auto centres a block that has a width.