Skip to content
Back to Concepts
CSS UniverseTrack 2: GeometryThe Box Model
1st Year CS Foundation · Core Track 2Core Concept 06

The CSS Box Model

In CSS, literally everything is a rectangular box. Learn how Content, Padding, Border, and Margin fit together, and why box-sizing: border-box is the single most important reset in web development.

1. The Mental Model

The Framed Painting Analogy

Think of every HTML element as an art piece hanging on a gallery wall:

1. Content

The Painting Canvas. Your text, image, or video lives here. Dimensions controlled by width and height.

2. Padding

The Cardboard Mat. Breathing room inside the frame. Still colored by your element's background-color!

3. Border

The Wooden Picture Frame. Wraps right around the padding edge with color, thickness, and style.

4. Margin

The Empty Wall Space. Invisible buffer pushing other paintings away. Never shows the background color!

2. The Great Math Battle

`box-sizing: border-box` vs `content-box`

Toggle between the two box sizing models below. Notice how in content-box, adding padding makes your element expand and break responsive grids!

Box Sizing:
margin: 20px
padding: 24px
Content (144px)
CSS width set to: 200px
Total Rendered Screen Width: 200px
Locked! The padding is absorbed inside your 200px constraint.
3. Margin Collapsing (The Weirdest CSS Quirk)

Why 20px + 30px = 30px (Not 50px!)

When two vertical block elements touch each other, their top and bottom margins collapse into a single margin equal to the larger of the two values.

h1 { margin-bottom: 30px; }
p { margin-top: 20px; }
/* The gap between h1 and p on screen is 30px, NOT 50px! */
Note: Horizontal margins never collapse! Flexbox and Grid items also never collapse margins.
4. Hands-on Box Model Workbench

Interactive Box Studio

Interactive Lab

Advanced Box Model Studio

Inspect box-sizing math (content-box vs border-box), test outline-offset, and experiment with vertical margin collapsing.

margin: 24px
Content152 × 52px
Declared (CSS)
200 × 100px
Content Area
152 × 52px
Rendered (Width)
200px
Total + Margin
248px
.box { box-sizing: border-box; width: 200px; height: 100px; padding: 20px; border: 4px solid #3b82f6; border-radius: 16px; margin: 24px; }
Next in Track 2

7. Display Modes

block, inline, inline-block, none, and modern flow-root formatting contexts.

Continue to Display Modes