Every Element Is a Box
Open DevTools on any website. Hover over an element. You'll see colored rectangles: the blue content area, green padding, the border line, and orange margin pushing outward. This is the box model — the fundamental abstraction that every CSS layout algorithm builds on.
Understanding the box model isn't just about knowing what padding does. It's about understanding how the browser calculates size, and why your element is 20 pixels wider than you expected.
The Four Layers
Every element generates a box with four concentric areas:
- Content — the text, image, or child elements
- Padding — transparent space between content and border
- Border — the visible (or invisible) edge of the element
- Margin — transparent space outside the border, pushing other elements away
Box Model Explorer
Toggle between content-box and border-box to see how the declared width is interpreted. Drag the sliders to adjust padding, border, and margin.
box-sizing Changes Everything
The default box-sizing: content-box means width and height only control the content area. Padding and border are added on top:
With box-sizing: border-box, the width includes padding and border. The content area shrinks to fit:
This is why every modern reset includes:
Margin Collapse
Margins have a behavior that surprises almost every developer at least once: vertical margins collapse. When two block-level elements stack vertically, their margins don't add — the larger margin wins.
Margin collapse only happens:
- Between block-level elements in normal flow
- On vertical margins (top/bottom), never horizontal (left/right)
- When there's no padding, border, or inline content between them
This interacts with the formatting context — which is the topic of the next stop on this line.
Why This Matters for System Design
The box model isn't just CSS trivia. It directly impacts:
- Layout performance: changing
widthorpaddingtriggers layout recalculation (reflow) for the element and its descendants. We'll cover this in depth in the Rendering Cycle stop. - Responsive design: percentage-based padding/margin is always relative to the containing block's width — even for vertical padding. This is the basis of aspect-ratio hacks.
- Scroll containers: the difference between
clientWidth(content + padding) andoffsetWidth(content + padding + border) catches developers constantly when building custom scroll behaviors.
Key Takeaways
- Every element is a box with content, padding, border, and margin layers
border-boxmakes sizing predictable — always use it- Vertical margins collapse; horizontal margins never do
- Size changes trigger reflow — a performance concern for animations