CSS margin collapse occurs when the margins of two adjacent elements overlap. In some cases, the resulting margin is the maximum of the two margins, while in other cases, the resulting margin is the minimum of the two margins.
There are three types of margin collapse:
Parent-child margin collapse
This occurs when the top or bottom margin of a child element overlaps with the top or bottom margin of its parent element. In this case, the resulting margin is the maximum of the two margins.
<body>
<div class="parent">
<div class="child">Child element</div>
</div>
</body>
.parent {
background-color: gray;
margin-top: 20px;
margin-bottom: 10px;
padding: 10px;
}
.child {
background-color: lightgray;
margin-top: 30px;
margin-bottom: 20px;
padding: 10px;
}
In this example, the child element has a top margin of 30px and the parent element has a bottom margin of 10px. Since these margins are adjacent, they will collapse and the resulting margin will be 30px (the maximum of the two margins). As a result, the child element will have a margin of 30px at the top and the parent element will have a margin of 30px at the bottom.
Adjacent-sibling margin collapse
This occurs when the top or bottom margin of one element overlaps with the top or bottom margin of an adjacent element. In this case, the resulting margin is the maximum of the two margins.
<body>
<div class="sibling">Sibling element 1</div>
<div class="sibling">Sibling element 2</div>
</body>
.sibling {
background-color: gray;
margin-top: 20px;
margin-bottom: 10px;
padding: 10px;
}
In this example, the two sibling elements have margins that are adjacent. Since the margins are not separated by padding, borders, or other elements, they will collapse and the resulting margin will be 20px (the maximum of the two margins). As a result, there will be a margin of 20px between the two sibling elements.
Empty-element margin collapse
This occurs when an empty element has a top or bottom margin. In this case, the margin collapses with any adjacent margins, and the resulting margin is the margin of the adjacent element.
<body>
<div class="element">Element with margin</div>
<div></div>
<div class="element">Element with margin</div>
</body>
.element {
background-color: gray;
margin-top: 20px;
margin-bottom: 10px;
padding: 10px;
}
In this example, there is an empty element between two elements with margins. Since the empty element has no content, its margin will collapse with the adjacent margins of the other elements, resulting in a margin of 20px between them.
It’s important to understand margin collapse when designing layouts in CSS, as it can affect the positioning of elements on the page. To prevent margin collapse, you can add padding to the parent element or use a border or an empty element to separate the two adjacent elements. Additionally, you can use the overflow
property to create a new block formatting context, which prevents parent-child margin collapse.