Every HTML element is treated as a rectangular box. Understanding the box model is crucial for layout!
From outside to inside: Margin → Border → Padding → Content
Padding is the space between content and border (inside the box).
| 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 |
Margin is the space outside the border (between elements).
When two vertical margins meet, they collapse into one (the larger value wins).
Border is the line between padding and margin.
Round the corners of your boxes!
The most important CSS property you'll learn!
*, *::before, *::after {
box-sizing: border-box;
}
Add this to every project! It makes width/height calculations predictable.
| 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) |
Hover over the box to see padding, margin, and border added!
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)
box-sizing: border-boxTotal Width = width (padding and border are included!)
Total Height = height (padding and border are included!)
Much easier to work with!