The Box Model
Every element is a box
In CSS, every element on the page is rendered as a rectangular box. Understanding the box model is crucial because it controls how much space each element takes up and how elements relate to each other.
The four layers
From inside to outside:
- Content — the actual text, image, or child elements.
- Padding — space between the content and the border.
- Border — a visible (or invisible) line around the padding.
- Margin — space between this element and neighboring elements.
CSS
.card {
width: 300px;
padding: 20px;
border: 1px solid #e2e8f0;
margin: 16px;
}With default box sizing, the total width of this card is:
300 (content) + 202 (padding) + 12 (border) = 342pxThat math gets annoying fast.
Fix it with border-box
By default, CSS sets
box-sizing: content-box, which means width only controls the content area. Padding and border are added on top.Almost every modern project overrides this:
CSS
*, *::before, *::after {
box-sizing: border-box;
}Now when you write
width: 300px, the element is exactly 300px wide — padding and border are included. This is a game-changer.Padding vs margin
- Padding creates space inside the element (between content and border).
- Margin creates space outside the element (between this element and others).
CSS
.button {
padding: 12px 24px; /* vertical | horizontal */
margin-bottom: 16px;
}A useful mental model: padding is like the cushion inside a picture frame, and margin is the wall space between frames.
Margin collapse
One gotcha: vertical margins between adjacent elements collapse. If one element has
margin-bottom: 20px and the next has margin-top: 30px, the gap between them is 30px, not 50px (the larger margin wins).This only happens with vertical margins, not horizontal ones, and it doesn't happen with flexbox or grid containers.
Key takeaway
Always add
box-sizing: border-box to your global styles. Think of every element as a box with content, padding, border, and margin. Once you internalize this, CSS layout becomes much less surprising.