The Box Model
Understanding the box model is one of the most important steps in learning CSS. Once you see how every element is a box with controllable layers, layout stops feeling mysterious.
The Four Layers
From the inside out:
- Content — the actual text, image, or inner elements
- Padding — space between the content and the border
- Border — a line around the padding and content
- Margin — space outside the border, separating this element from others
.card {
padding: 1.5rem; /* space inside */
border: 1px solid #e5e7eb;
margin: 1rem 0; /* space outside */
}
Width and Height
By default, width and height only apply to the content area. Padding and border are added on top of that, which can cause unexpected sizing.
.box {
width: 300px;
padding: 20px;
border: 2px solid black;
/* actual rendered width: 300 + 20 + 20 + 2 + 2 = 344px */
}
box-sizing: border-box
The fix is box-sizing: border-box. This makes width and height include padding and border — so what you set is what you get.
*,
*::before,
*::after {
box-sizing: border-box;
}
.box {
width: 300px;
padding: 20px;
border: 2px solid black;
/* actual rendered width: exactly 300px */
}
Always add box-sizing: border-box as a global reset. Nearly every CSS framework does this by default, and it prevents a huge class of sizing bugs.
Padding Shorthand
You can set padding on all four sides at once using shorthand:
/* All sides */
padding: 1rem;
/* Top/bottom, left/right */
padding: 0.5rem 1rem;
/* Top, right, bottom, left (clockwise) */
padding: 0.25rem 1rem 0.5rem 0.75rem;
The same shorthand applies to margin.
Margin Collapse
When two vertical margins touch, they collapse into a single margin equal to the larger of the two. This only happens vertically (top/bottom), not horizontally.
/* These two paragraphs won't have 2rem of space between them —
only 1rem, because the margins collapse */
p {
margin-bottom: 1rem;
margin-top: 1rem;
}
Negative Margins
Margins can be negative, pulling an element toward or past its neighbors. This is occasionally useful for overlapping elements:
.overlap {
margin-top: -1rem;
}
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.