CSS Margin Collapse
When the top and bottom margins of block elements meet, they combine into a single margin instead of adding together.
Margin collapse is a behavior that surprises many people. When two vertical margins touch, the browser keeps only the larger of the two rather than stacking them. This applies to the space between stacked block elements and, in some cases, between a parent and its first or last child.
Margins between siblings
If one paragraph has a 30px bottom margin and the next has a 20px top margin, the gap between them is 30px, not 50px. The smaller margin is absorbed into the larger one.
Only the larger margin wins
<!DOCTYPE html>
<html>
<head>
<style>
.intro {
margin-bottom: 30px;
}
.next {
margin-top: 20px;
}
/* The visible gap between them is 30px */
</style>
</head>
<body>
<p class="intro">This is the intro paragraph.</p>
<p class="next">This paragraph follows right after.</p>
</body>
</html>When collapse does not happen
- Horizontal (left and right) margins never collapse.
- Margins on floated or absolutely positioned elements do not collapse.
- A parent with padding, a border, or overflow set to something other than visible separates its margin from a child's.
Padding stops the collapse
<!DOCTYPE html>
<html>
<head>
<style>
.panel {
padding-top: 1px;
}
.panel h2 {
margin-top: 40px;
}
/* The h2 margin now stays inside the panel */
</style>
</head>
<body>
<div class="panel">
<h2>Section heading</h2>
<p>Panel content goes here.</p>
</div>
</body>
</html>Note: A common way to avoid collapse surprises is to set margin in one direction only, for example only margin-bottom, so spacing is predictable.