Box model, units and text
The box model
Goal: Calculate the size of an element from content, padding, border and margin · 11 min
Every element is a rectangular box with four layers, from the inside out:
- content: text or children (size set by
widthandheight), - padding: space inside the border, around the content,
- border: the line around the padding,
- margin: transparent space outside the border that separates the element from its neighbours.
By default (box-sizing: content-box) width sets the content width only. A box with width: 200px; padding: 10px; border: 5px solid; is 200 + 2·10 + 2·5 = 230px wide on screen (plus margins).
Most developers set box-sizing: border-box: then width includes padding and border, so the same box is 200px wide in total and the content shrinks to 170px. It makes layouts predictable:
*, *::before, *::after { box-sizing: border-box; }
Shorthands run clockwise from the top: margin: 10px 20px 30px 40px means top 10, right 20, bottom 30, left 40. Two values: vertical | horizontal. One value: all four sides. margin: 0 auto centres a block with a set width.
Margin collapsing: vertical margins of adjacent block elements do not add; the larger one wins (20px under 30px leaves 30px). Horizontal margins never collapse.
Worked example: Total width of a box
- CSS: width: 300px; padding: 20px; border: 2px solid; (content-box)
- Horizontal: 300 + 2·20 + 2·2 = 344px.
- With box-sizing: border-box the same declarations give exactly 300px in total.
.box {
width: 300px;
padding: 20px;
border: 2px solid;
}