root@coding-prodigies:~# โ–Š
// lesson 3 of 12 ยท 16 min

The box model

โš‘ Report an issue with this lesson

Every HTML element is a rectangular box made of four layers, from the inside out: content, padding, border, margin.

.card {
  padding: 16px;       /* space inside the border */
  border: 1px solid #ccc;
  margin: 24px;          /* space outside the border */
}

By default, width/height apply only to the content -- padding and border get added on top, which trips people up constantly. Fix it globally with:

* {
  box-sizing: border-box;
}

With border-box, width includes padding and border, so a 300px-wide box stays 300px no matter how much padding you add.

Margin collapsing

One of the box model's stranger behaviors: when two block elements stack vertically, their top/bottom margins don't add together -- the browser collapses them down to whichever margin is larger.

p {
  margin-top: 20px;
  margin-bottom: 20px;
}

Two paragraphs in a row here end up with 20px of space between them, not 40px. This only happens with vertical margins between block elements in normal flow (never with padding, and never horizontally), but it explains a lot of "why isn't my spacing what I calculated" confusion. If you need guaranteed spacing regardless of collapsing, Flexbox's gap (covered next lesson) sidesteps the issue entirely.

Auto margins for centering

.card {
  width: 400px;
  margin: 0 auto;
}

Setting left and right margin to auto on a block element with a fixed width splits the remaining horizontal space evenly on both sides -- the classic way to center a block horizontally before Flexbox existed, and still extremely common today.

Negative margins

Margins can be negative, which pulls an element closer to (or overlapping) its neighbors instead of pushing it away:

.overlap {
  margin-top: -10px;
}

Use sparingly and deliberately -- it's a real technique for specific overlap effects, but reaching for it to "fix" spacing that's wrong for a different reason usually just hides the actual bug.

Debugging the box model

When spacing looks wrong, open your browser's DevTools (right-click โ†’ Inspect) and look at the box model diagram in the Elements/Styles panel -- it shows the exact content, padding, border, and margin sizes for the selected element, which is almost always faster than guessing from the CSS alone.

Try it yourself

Exercise: Add box-sizing: border-box to .box, then increase its padding to 30px.
html
Live preview
// that was the last free lesson

9 more lessons โ€” including Project: style your portfolio page โ€” plus a certificate are waiting.

Unlock the full course โ€” $29.99