The Box Model
Every element on a page is a rectangular box made of four layers: the content, padding around it, a border, and margin outside. Understanding how these layers add up — and how margins interact — is fundamental to controlling spacing and size in CSS.
The four layers
- Content — where text and child elements go, sized by
widthandheight. - Padding — space inside the border; it shows the element's background.
- Border — a line around the padding.
- Margin — transparent space outside the border, pushing other elements away.
How width adds up
By default (box-sizing: content-box), width sets only the content. Padding and border are added on top:
width 200 + padding 20 + 20 + border 6 + 6 = 252px total
That surprises almost everyone, so most projects switch to box-sizing: border-box, where width includes padding and border (lesson 17).
Margin and padding shorthands
| Values | Meaning |
|---|---|
| 1 | All four sides |
| 2 | Top & bottom, left & right |
| 3 | Top, left & right, bottom |
| 4 | Top, right, bottom, left — clockwise from the top |
Individual sides have their own properties: margin-top, padding-left and so on. Logical versions like padding-inline and margin-block adapt to the writing direction (lesson 34).
Centring with auto margins
For a block with a set width, margin-inline: auto (or margin: 0 auto) splits the remaining space equally on both sides.
Margin collapsing
When vertical margins of adjacent blocks touch, they collapse into a single margin equal to the larger one. This also happens between a parent and its first or last child, when nothing (padding, border, content) separates them — a frequent source of confusion when a child's top margin seems to "leak" out of its parent.
Margins don't collapse horizontally, or inside flex and grid containers. Many developers avoid the issue by using margin in only one direction (for example, only margin-block-end) or by using gap in flex and grid layouts.
Negative margins
Negative margins pull an element outward or pull neighbours closer — useful in moderation.
Padding vs margin
- Use padding for space inside a component — between its border and its content. Padding is part of the clickable, coloured area.
- Use margin (or a parent's
gap) for space between components.
Inline elements are different
For inline elements, vertical margins are ignored and vertical padding doesn't affect layout. Use display: inline-block if you need full box behaviour.