Do you see anything wrong in below image? 👀
No? 🧐
Let me give you hint, Parent margin is missing.
I have made a minor change, do you see what I am talking about now?
This is something that tripped me up recently — turns out it’s caused by a little CSS behavior called margin collapsing.
🤔 So, what is Margin Collapsing?
As per MDN:
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. Note that the margins of floating and absolutely positioned elements never collapse.
In simpler terms:
If two vertical margins meet (like one element’s bottom and the next one’s top), only the larger one is applied, not both.
This can make it feel like your margins are “disappearing” — which is exactly what I experienced!
🔧 How to Fix It?
One of the simplest ways is to change the display of the parent element to flex or grid.
This stops margin collapsing from happening altogether. As you see in second image.
.parent {
display: flex; /* or grid */
}
🌱 Why This Mattered to Me
I stumbled upon this while debugging a weird layout issue. Margins weren’t stacking like I expected, and it made me question everything 😅
After some digging, I found this gem of a page:
👉 Mastering Margin Collapsing - MDN
Highly recommended read if you’ve ever felt CSS was gaslighting you.
✅ TL;DR
If vertical margins seem to “disappear”, margin collapsing might be the culprit
Happens between block elements’ top/bottom margins
Avoid it using display: flex, grid, or some padding
Would love to hear if you’ve faced this before — or if this helped you spot a sneaky bug. Let me know below! 👇
Top comments (0)