Lesson 5 of 50
cssThe Box Model
10 mins
Course progress10%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 5 of 50
css10 mins
Keep these ideas in mind as you work through the lesson.
Every element in the layout world is a rectangular box composed of four concentric layers:
+---------------------------+
| margin (transparent) |
| +---------------------+ |
| | border | |
| | +---------------+ | |
| | | padding | | |
| | | +----------+ | | |
| | | | content | | | |
| | | +----------+ | | |
| | +---------------+ |
| +---------------------+ |
+---------------------------+
A common source of layout bugs is forgetting the margin that collapses with its parent’s margin, or adding padding that pushes the element beyond the width you designed.
.box {
width:200px; /* content width */
padding:20px; /* inner space */
border:5px solid #333; /* border thickness */
margin:30px; /* outer space */
background:#f4f4f4;
}
Use the browser inspector (Chrome DevTools → Computed → Box Model) to see the numbers update live.
box-sizingSet border‑box globally so the width you declare already includes padding and border:
*, *::before, *::after { box-sizing:border-box; }
Now the .box above will stay exactly 200 px wide, no matter how much padding you add.