π¨
EPISODE 03
content Β· padding Β· border Β· margin Β· box-sizing
The Box Model
Every element is a box made of four layers. Master padding vs margin, box-sizing: border-box, and how negative margins behave.
box modelpaddingmarginborderbox-sizing
Duration
β± About 1 hour
Level
π Beginner
Prerequisite
π― css-01
OUTCOME
Predict any element's outer dimensions
What you'll learn
- 1Distinguish content, padding, border, and margin
- 2Use box-sizing: border-box correctly
- 3Recognize margin collapse and how to prevent it
- 4Apply border-radius and outline appropriately
1. The Four Layers
text
ββ margin (outside, transparent) βββββββββββββββ
β ββ border ββββββββββββββββββββββββββββββββ β
β β ββ padding (inside, takes bg) ββββββ β β
β β β content (text/images) β β β
β β ββββββββββββββββββββββββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββ- padding β space inside the border, shares the background
- border β the visible edge
- margin β space between this element and others, transparent
2. box-sizing: border-box
css
* { box-sizing: border-box; } /* start every project with this */
.card {
width: 300px;
padding: 20px;
border: 1px solid #e5e7eb;
}
/* width: 300px now INCLUDES padding + border, not just content */β οΈ
Without border-box, .card above is actually 342px wide (300 + 20*2 + 1*2). That mismatch is the #1 source of layout bugs.
3. Margin Collapse
Adjacent vertical margins collapse into the larger one. Two paragraphs with margin: 16px end up with 16px between them, not 32px.
- Prevent collapse with padding instead of margin
- Or wrap content in an element with overflow: auto
- Flex/Grid children do not collapse β another reason to use them
4. border-radius and outline
css
.avatar {
width: 64px;
height: 64px;
border-radius: 50%; /* perfect circle */
}
.btn:focus-visible {
outline: 2px solid #2563eb;
outline-offset: 2px; /* outline does NOT affect layout */
}Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β