Episode 36 of 53
Control Margins in CSS
Master the margin property — spacing, auto centering, and margin collapse.
The margin property controls the space outside an element, creating distance between it and neighboring elements.
Setting Margins
/* All four sides */
.box { margin: 20px; }
/* Top/bottom and left/right */
.box { margin: 20px 40px; }
/* Top, left/right, bottom */
.box { margin: 10px 20px 30px; }
/* Top, right, bottom, left (clockwise) */
.box { margin: 10px 20px 30px 40px; }
Individual Sides
.box {
margin-top: 1rem;
margin-right: 2rem;
margin-bottom: 1rem;
margin-left: 2rem;
}
Auto Margins for Centering
/* Center a block element horizontally */
.container {
width: 800px;
margin: 0 auto;
}
Margin Collapse
When two vertical margins meet, they collapse — only the larger one applies:
.box-a { margin-bottom: 20px; }
.box-b { margin-top: 30px; }
/* Space between them = 30px (not 50px) */
Negative Margins
Margins can be negative, pulling elements closer or overlapping:
.overlap {
margin-top: -20px; /* Pulls element UP by 20px */
}
Best Practices
- Use
margin: 0 autofor centering - Be aware of margin collapse
- Prefer one direction for consistency (e.g., always
margin-bottom)