CSS - margin collapsing
In this article, we would like to show you what is margin collapsing in CSS.
Margin collapsing is a situation where browsers overlap margins of two neighbouring elements. The distance between two elements is then margin with larger value.

In this example, we we create three paragraphs with different margins.
When you use Chrome Developer Tools to inspect the paragraphs, you can see their margins overlap leaving the space between paragraphs equal to the largest margin (not the sum of two margins as could be expected).
xxxxxxxxxx
<html>
<head>
<style>
p {
margin: 20px 10px 30px 10px;
}
p.paragraph-1 {
background: #adadff;
}
p.paragraph-2 {
background: orange;
}
p.paragraph-3 {
background: #7dd96d;
}
</style>
</head>
<body>
<p class="paragraph-1">Paragraph 1</p>
<p class="paragraph-2">Paragraph 2</p>
<p class="paragraph-3">Paragraph 3</p>
</body>
</html>
Note: the final space between each paragraph is calculated as
max(20px, 10px)
so it is20px
.
In this example, you can see animated margins preview created from the above example source code. Elements are selected with Chrome Developer Tools showing areas covered by margins. We can see the margins for paragraps are overlapped.
