CSS — Lesson 3
Box Model & Spacing
Understanding margins, padding, and borders.
Box Model & Spacing
Every HTML element is a rectangular box. The CSS Box Model defines how spacing and sizing work.
The Box Model
Margin
Border
Padding
Content
Margin
Space outside the element, pushing other elements away.
.card {
margin: 20px; /* all sides */
margin: 10px 20px; /* top/bottom left/right */
margin: 10px 20px 30px 40px; /* top right bottom left */
}
Padding
Space inside the element, between content and border.
.card {
padding: 16px;
padding: 12px 24px;
}
Border
A line around the element, between margin and padding.
.card {
border: 2px solid #333;
border-radius: 8px; /* Rounded corners */
}
box-sizing
The box-sizing property changes how width/height are calculated.
- content-box (default): width applies only to content area
- border-box: width includes padding and border (recommended)
/* Reset for all elements */
* {
box-sizing: border-box;
}
Margin Collapse
Vertical margins between adjacent elements collapse into the larger of the two. Horizontal margins do not collapse.
Tip: Always set
box-sizing: border-box on all elements - it makes sizing much more predictable.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →