Jan's Development Microblog
Go back to blog overview

The strange behavior of Margin Collapsing

— by Jan Valkenburg in CSS
Read time: 3 min

Margin collapsing in CSS can be confusing. While vertical margins collapse, horizontal ones don’t. Understanding this helps avoid unexpected spacing issues.

For years of writing CSS, I was never caught off guard by the collapsing margins issue. During a recent development session, I was fixing some whitespace and was confused about why my spacing was off. The CSS code was as follows. Yes, I'm using px there —not by choice, as you should never use px in modern web development.​

p { margin-bottom: 1rem; }
p:has(.btn) { margin-top: 48px; }

You would expect that 16 + 48 = 64, but that was not the case. The spacing was 48px (16 + 48 = 48). Strangely, this is actually the correct behavior in CSS. Margins collapse when a margin-bottom and a margin-top from two elements touch each other. In such cases, the larger margin takes precedence, and that value is used as the spacing between the two elements.​

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. - MDN Webdocs

Not working with margin-right vs margin-left

So, my first thought was that if this behavior applies to margin-bottom vs. margin-top, would it also work for margin-right vs. margin-left? However, after a quick test, this does not seem to be the case. For the test, I used the following code:​

​<div class="el-1"></div>
<div class="el-2"></div>
<style>
.el-1, .el-2 {
display: inline-block;
inline-size: 6rem;
aspect-ratio: 4/1;
background-color: rebeccapurple;
}
.el-1 { margin-right: 1rem; }
.el-2 { margin-left: 2rem; }
</style>

The result looked like this: the green spacing represents margin-right, and the blue one represents margin-left.​

While this behavior makes sense, it is still confusing. You would expect that if margins collapse vertically, they should also collapse for horizontal blocks—but that’s not the case.​

Final word

Margin collapsing is one of those odd CSS rules that, in my opinion, should never have been implemented. But since it's there, we have to deal with it when we encounter it. Now that we understand how it works, we can find ways to work around it.