Lesson 4 of 8 · 8 min · 2 hands-on steps
The Box Model
Every element is a box. Control its size and spacing with padding, border and margin.
Every element is a box
From the inside out:
- Content: the text or image
- Padding: space between content and border
- Border: the line around it
- Margin: space between this box and others
Try it: drag the sliders
Total width on screen: 160px (padding and border fit inside the width with border-box).
The one line every project starts with
* { box-sizing: border-box; }
With the default (content-box), width: 300px plus padding: 20px makes a box 340px wide, which surprises everyone. border-box makes width mean "the whole box". Almost every professional stylesheet starts with this line.
Shorthand
padding: 10px; /* all four sides */
padding: 10px 20px; /* top+bottom, left+right */
padding: 5px 10px 15px 20px; /* top, right, bottom, left (clockwise) */
margin: 0 auto; /* no top/bottom margin, center horizontally */
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · Space it out
Give .box:
padding: 20px(space inside the border)margin: 30px(space outside the border)border: 4px solid black
<div class="box">I'm a box</div>
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Center a card
Make .card exactly 300px wide (including padding and border) and center it horizontally with margin: 0 auto.
<div class="card">Centered!</div>
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
Which is the space inside the border, around the content?
What does box-sizing border-box change?
Create a free account to track your progress.