The Box Model — Margin, Padding, Border
Everything Is a Box
Every element renders as a rectangle with four layers, inside out:
- Content — the text/image itself (width × height)
- Padding — space between content and border (has the background)
- Border — the edge
- Margin — transparent space pushing other boxes away
.card {
width: 300px;
padding: 24px;
border: 1px solid #E5E7EB;
margin: 16px;
}box-sizing: border-box — Always
By default (content-box), width means the content width — padding and border get added on top, so the card above is actually 350px wide. Nobody wants that math:
*, *::before, *::after {
box-sizing: border-box; /* width now includes padding + border */
}With border-box, width: 300px means the box is 300px, full stop. Every modern codebase sets this globally — it’s line one of every reset.
Shorthand Notation
padding: 16px; /* all four sides */
padding: 8px 16px; /* vertical | horizontal */
padding: 8px 16px 24px; /* top | horizontal | bottom */
padding: 8px 16px 24px 32px; /* top right bottom left — clockwise */
margin: 0 auto; /* classic horizontal centering (needs a width) */
border: 1px solid #E5E7EB; /* width style colour */
border-radius: 12px; /* rounded corners */
border-radius: 50%; /* circle (on a square box) */Margin Collapsing — the Classic Surprise
Vertical margins between stacked elements don’t add — the larger one wins:
h2 { margin-bottom: 24px; }
p { margin-top: 16px; }
/* gap between them: 24px, not 40px */Collapsing only affects vertical margins of block elements in normal flow — flex and grid children never collapse, one of many reasons modern layout feels saner.
Spacing Strategy
Padding for space inside a thing; margin (or better, the parent’s gap) for space between things. A common modern pattern — give components zero outer margin and let layout containers own the spacing:
.stack > * + * {
margin-top: 1rem; /* "lobotomised owl" — space between siblings only */
}overflow
.box {
overflow: hidden; /* clip content that doesn't fit */
overflow-y: auto; /* scrollbar only when needed */
}
.title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /* the one-line "…" pattern */
}