Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
The margin property adds space outside an element’s border, creating distance between elements.
Individual Properties
Set margins on specific sides:
.box {
margin-top: 20px;
margin-right: 15px;
margin-bottom: 20px;
margin-left: 15px;
}
Shorthand Syntax
The margin shorthand depends on how many values you provide:
1 value - All sides
margin: 20px;
/* top: 20px, right: 20px, bottom: 20px, left: 20px */
2 values - Vertical | Horizontal
margin: 20px 10px;
/* top: 20px, right: 10px, bottom: 20px, left: 10px */
3 values - Top | Horizontal | Bottom
margin: 20px 10px 30px;
/* top: 20px, right: 10px, bottom: 30px, left: 10px */
4 values - Top | Right | Bottom | Left (clockwise)
margin: 20px 10px 30px 5px;
/* top: 20px, right: 10px, bottom: 30px, left: 5px */
Using auto for Centering
margin: auto lets the browser calculate margins automatically. Combined with a width, it centers block elements:
.centered {
width: 600px;
margin: 0 auto; /* Center horizontally */
}
Negative Margins
Margin is unique—it can be negative:
.overlap {
margin-top: -20px; /* Move up, overlapping previous element */
}
- Negative top: moves element up
- Negative bottom: pulls following elements up
- Negative left: moves element left
- Negative right: expands content area
Margin Collapse
Vertical margins between adjacent elements collapse into a single margin (the larger one wins):
.box1 { margin-bottom: 20px; }
.box2 { margin-top: 30px; }
/* Actual space between them: 30px, not 50px */
This only happens with vertical margins, not horizontal.
Lessons in this unit:
| 0: | Introduction |
| 1: | Understanding the CSS Box Model |
| 2: | How to Use CSS Box Sizing |
| 3: | ▶︎ How to Use CSS Margin |
| 4: | How to Use CSS Padding |
| 5: | How to Style CSS Borders |