← Back to Examples

The CSS Box Model

Every HTML element is treated as a rectangular box. Understanding the box model is crucial for layout!

1. Box Model Visualization

From outside to inside: MarginBorderPaddingContent

MARGIN (red)
BORDER (dashed)
PADDING (green)
CONTENT (blue)

2. Padding

Padding is the space between content and border (inside the box).

padding: 20px (all sides equal)
padding: 10px 30px (top/bottom, left/right)
padding: 10px 20px 30px 40px (top, right, bottom, left - clockwise)
Property Description
padding: 20px All four sides
padding: 10px 20px Top/bottom, Left/right
padding: 10px 20px 30px Top, Left/right, Bottom
padding: 10px 20px 30px 40px Top, Right, Bottom, Left (clockwise)
padding-top, padding-right, etc. Individual sides

3. Margin

Margin is the space outside the border (between elements).

margin: 20px (space around the box)
margin: auto centers horizontally!

Margin Collapse

When two vertical margins meet, they collapse into one (the larger value wins).

First box with margin: 30px 0
Second box with margin: 30px 0 (margins collapse, not 60px gap!)

4. Border

Border is the line between padding and margin.

border: 3px solid #2c3e50
border: 3px dashed #e74c3c
border: 3px dotted #27ae60
border: 5px double #3498db
Different borders on each side!

Border Radius

Round the corners of your boxes!

border-radius: 10px
border-radius: 25px
50%

5. Box Sizing

The most important CSS property you'll learn!

content-box
width: 200px
+ padding: 20px
+ border: 10px
= 260px total!
border-box
width: 200px
(includes padding & border)
= 200px total!

Best Practice: Universal Box Sizing Reset

*, *::before, *::after {
    box-sizing: border-box;
}

Add this to every project! It makes width/height calculations predictable.

6. Width and Height

Property Description
width: 300px Fixed width
width: 50% 50% of parent width
max-width: 600px Won't exceed 600px
min-width: 200px Won't shrink below 200px
height: auto Height based on content (default)

7. Interactive Demo

Hover over the box to see padding, margin, and border added!

Hover me!
(Watch the box model change)

8. Calculating Total Size

With box-sizing: content-box (default)

Total Width = width + padding-left + padding-right + border-left + border-right

Total Height = height + padding-top + padding-bottom + border-top + border-bottom

(Margin adds space but isn't part of the element's size)

With box-sizing: border-box

Total Width = width (padding and border are included!)

Total Height = height (padding and border are included!)

Much easier to work with!


← Back to Examples