Lesson Content
Every HTML element is a rectangular box. The CSS Box Model describes the four layers that make up that box, from inside to outside:
1. Content — the actual text, image, or other content inside the element 2. Padding — transparent space between the content and the border 3. Border — a visible line around the padding and content 4. Margin — transparent space outside the border, separating this element from others
Padding vs Margin: Padding is inside the element (affects background colour). Margin is outside the element (always transparent).
The box-sizing problem: By default, when you set `width: 300px`, that only applies to the content. Padding and border are added on top, making the element wider than expected.
The fix: box-sizing: border-box makes the width include padding and border. Most developers apply this to every element by default using * { box-sizing: border-box; }.
Understanding the box model is the single most important concept in CSS layout. Every spacing issue you'll ever debug comes back to this.
/* Apply border-box to everything */
* {
box-sizing: border-box;
}
.card {
width: 320px;
/* Content area */
background-color: white;
/* Padding: space inside */
padding: 24px 32px;
/* Border */
border: 2px solid #E8E2D9;
border-radius: 16px;
/* Margin: space outside */
margin: 16px;
}
/* Shorthand: top/bottom left/right */
.section {
padding: 64px 24px;
margin: 0 auto; /* centres a block element */
}Finished this lesson?
Mark it complete to track your progress through the course.
Learning Objectives
- 1Understand the four layers of the CSS box model
- 2Control spacing with margin and padding
- 3Add borders and understand how they affect size
- 4Use box-sizing: border-box to simplify sizing
0 of 31 lessons done