Margin Collapse in CSS: What It Is and How It Works
margin collapse happens when the vertical margins of two or more adjacent elements combine into a single margin instead of adding up. This usually occurs between parent and child elements or between siblings, making layout spacing simpler and avoiding extra gaps.How It Works
Imagine two boxes stacked vertically, each with some space (margin) above or below. Instead of adding those spaces together, CSS merges them into one space equal to the largest margin. This is called margin collapse.
Think of it like two friends standing close together: instead of both taking a big step back, they agree to take just one step back equal to the bigger step. This keeps the space neat and avoids double gaps.
Margin collapse mainly happens with vertical margins (top and bottom), not horizontal ones. It occurs between adjacent siblings or between a parent and its first or last child if no border or padding separates them.
Example
This example shows two boxes with vertical margins that collapse into one margin.
html, body {
margin: 0;
padding: 0;
}
.container {
background-color: #f0f0f0;
padding: 10px;
}
.box {
background-color: #4a90e2;
color: white;
margin-bottom: 30px;
padding: 20px;
font-family: Arial, sans-serif;
}
.box + .box {
margin-top: 50px;
}When to Use
Understanding margin collapse helps you control vertical spacing in layouts without unexpected gaps. It is useful when you want consistent spacing between sections or elements without doubling the space.
For example, when building a blog post, margin collapse ensures the space between paragraphs or headings stays neat and predictable. It also helps when nesting elements inside containers, so the container's margin doesn't add extra space beyond what you expect.
If you want to prevent margin collapse, you can add padding, borders, or use CSS properties like overflow: hidden on the parent.
Key Points
- Margin collapse only affects vertical margins (top and bottom).
- Adjacent vertical margins combine into one margin equal to the largest.
- It happens between siblings and between parent and child elements without borders or padding.
- Margin collapse helps avoid extra space and keeps layouts tidy.
- You can prevent collapse by adding padding, borders, or using certain CSS properties.