Lesson 7: Box model
Padding, border, and margin make space around things.
What you'll learn
- What padding, border, and margin do
- Why
box-sizing: border-boxhelps - How to space cards
Explain like I'm 10
Think of a gift box: padding is the bubble wrap, border is the box, margin is the space outside.
.card { padding: 12px; border: 2px solid #ccc; margin: 10px; }
Content, padding, border, margin
Every element has a content box (the actual content), then padding (space inside the element), border (the visible edge), and margin (space outside). These together form the box model.
/* content */
div { width: 200px; }
/* padding */
.box { padding: 12px; }
/* border */
.box { border: 2px solid #ccc; }
/* margin */
.box { margin: 16px; }
How width/height interact with padding & border
By default, width sets the content box only. Adding padding or border increases the total visual size. This can cause surprises when you expect an element to stay a fixed width.
box-sizing: border-box
Setting box-sizing: border-box makes the width and height include padding and border. This prevents size surprises and is recommended for predictable layouts.
/* global reset */
*, *::before, *::after { box-sizing: border-box; }
/* now width includes padding and border */
.card { width: 300px; padding: 16px; border: 2px solid #ccc; }
Spacing patterns
Use consistent spacing: stack spacing (gap between vertical items), and consistent margin rules. For example, give list items a consistent margin-bottom or use CSS gap on flex/grid containers.
Overflow basics
If content is larger than its box, it may overflow. Use overflow: auto or hidden to control it, and be mindful of scrollbars.
.scroll { max-height: 200px; overflow: auto; }
Example: two boxes
<div class="card">First box with padding and border</div>
<div class="card">Second box with margin and border</div>
/* CSS (visual comments) */
.card { width: 300px; padding: 16px; border: 2px solid #cbd5f5; margin-bottom: 16px; }
Common mistakes & fixes
- Unexpected width: Forgetting padding in width calculation — use
border-boxto avoid this. - Margin collapse: Vertical margins between elements can collapse; adding padding or border prevents collapse.
- Overflowing content: Use
overflowrules or increase container size.
Practice tasks
- Create two cards and tweak padding, border and margin to see the effect.
- Add
box-sizing: border-boxglobally and observe differences. - Make a fixed-height box with overflowing content and add a scrollbar with
overflow: auto.
Mini challenge
- Add a third card.
- Make the cards wider.