Chapter 4 of 14
~11 minThe Box Model
Every element in CSS is a rectangular box made of content, padding, border, and margin - understanding how these stack is the foundation of all CSS layout.
Content, Padding, Border & Margin
Content is the actual text or child elements. Padding is space inside the border, between the border and the content. Border wraps around the padding. Margin is space outside the border, separating the element from its neighbors.
Try it yourself
<div class="box">Content area, surrounded by padding, then border, then margin.</div>
content-box vs border-box
By default (box-sizing: content-box), width/height set only the content area's size - padding and border are added on top, so a 200px-wide box with 20px padding and a 5px border actually takes up 250px. box-sizing: border-box instead makes width/height include padding and border, so the box stays exactly 200px no matter how much padding you add.
Because border-box math is far more predictable, nearly every project sets a global reset like *, *::before, *::after { box-sizing: border-box; } at the very top of the stylesheet.
Try it yourself
Both boxes set width: 200px, but render differently<div class="content-box">content-box: renders wider than 200px</div> <div class="border-box">border-box: stays exactly 200px</div>
Margin Collapsing
When two block-level elements stack vertically, their top and bottom margins can "collapse" into a single margin equal to the larger of the two, instead of adding together. This only happens for vertical margins between normal-flow siblings (or a parent and its first/last child in some cases) - it never happens horizontally, and it doesn't happen if padding, border, or a clearfix separates them.
Try it yourself
<div class="a">Box A (margin-bottom: 40px)</div> <div class="b">Box B (margin-top: 20px) - gap is 40px, not 60px, because the margins collapsed</div>
Coding challenge
Set box-sizing: border-box globally, then build a 300px-wide box with 24px padding and a 4px border that still renders at exactly 300px.
<div class="box">Exactly 300px wide</div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. In the default content-box model, what does the width property size?
2. Why do most projects set box-sizing: border-box globally?
3. What is margin collapsing?
4. Which order do the box model layers appear, from the inside out?