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:

  1. Content: the text or image
  2. Padding: space between content and border
  3. Border: the line around it
  4. Margin: space between this box and others

Try it: drag the sliders

📐 The box model
margin
padding
content

Total width on screen: 160px (padding and border fit inside the width with border-box).

Switch box-sizing to content-box and watch the total width jump.

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 done

Step 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.

✅ Check your understanding

  1. Which is the space inside the border, around the content?

  2. What does box-sizing border-box change?

Create a free account to track your progress.