The Box Model
Prerequisites: Units and values
Every element is a rectangular box made of four layers:
┌──────────────── margin ────────────────┐
│ ┌───────────── border ─────────────┐ │
│ │ ┌────────── padding ─────────┐ │ │
│ │ │ │ │ │
│ │ │ content │ │ │
│ │ │ │ │ │
│ │ └────────────────────────────┘ │ │
│ └──────────────────────────────────┘ │
└────────────────────────────────────────┘
- Content — the text or images; sized by
widthandheight. - Padding — space inside the border; the background shows through.
- Border — a line around the padding.
- Margin — space outside the border, between this box and others; always transparent.
content-box vs border-box
By default (box-sizing: content-box), width sets only the
content. Padding and border are added on top:
<style>
.box { width: 200px; padding: 20px; border: 5px solid; margin: 10px; }
.border-box { box-sizing: border-box; }
</style>
<div class="box">content-box</div>
<div class="box border-box">border-box</div>
<script>
for (const el of document.querySelectorAll(".box")) {
const s = getComputedStyle(el);
const content = el.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingRight);
console.log(el.textContent.padEnd(11), "box width:", el.offsetWidth, "content width:", content);
}
</script>
content-box box width: 250 content width: 200
border-box box width: 200 content width: 150
content-box: 200 + 2 × 20 padding + 2 × 5 border = 250px wide.border-box: the box is 200px wide, and the content shrinks to 150px to make room.- Margins are never part of the width.
border-box is far easier to reason about, so almost every project
starts with this reset:
*,
*::before,
*::after {
box-sizing: border-box;
}
See it in DevTools
Select an element and look at the box model diagram in the Computed tab: content size in the middle, with padding, border, and margin around it. Hovering an element on the page shows padding in green and margin in orange.
Practice
With box-sizing: border-box, a .sidebar has width: 300px,
padding: 24px, and border-left: 4px solid. How wide is its content
area?
Show solution
300 − 24 − 24 − 4 = 248px. With border-box, padding and border
come out of the 300px; only the left border exists, so it's subtracted
once.