Lesson 6 of 18
CSS Box Model 🔶
What You'll Learn
- Understand margin, border, padding, and content
- Use box-sizing: border-box
- Space elements correctly on a page
Every Element Is a Box
In CSS, every element is treated as a rectangular box with four layers:
- ● Content — the actual text or image
- 🔷 Padding — space between content and the border (inside)
- 🔶 Border — the visible line around the element
- □ Margin — space outside the border (between elements)
Box Model in CSS
CSS
.card {
/* Content size */
width: 300px;
/* Padding - inside spacing */
padding: 20px; /* all sides */
padding: 10px 20px; /* top/bottom left/right */
padding-top: 10px;
/* Border */
border: 2px solid #00C853;
border-radius: 12px; /* rounded corners */
/* Margin - outside spacing */
margin: 16px; /* all sides */
margin: 0 auto; /* center horizontally */
}box-sizing: border-box
By default, padding and border are added to the width, making elements bigger than expected. Fix this by adding to the top of your CSS:
CSS
*, *::before, *::after {
box-sizing: border-box; /* padding included in width */
}Always Add This
Professional developers put box-sizing: border-box at the top of every stylesheet. It makes layout much more predictable!
Style a Card
Create a div with class card. Give it a background color, padding of 24px, border-radius of 12px, a border, and margin: 20px auto. Put a heading and paragraph inside. Notice how padding and margin affect the spacing!
Quick Check
What does padding do?
What does margin: 0 auto do?
What does box-sizing: border-box do?