Collapsing Margin between parent and child

Vaibhav Mande
2 min readNov 23, 2021

--

Photo by Kaleidico on Unsplash

Today, I would like to invite you to explore this problem with me. I spent a lot of hours understanding the root cause and hopefully, this saves your time if you come across the same.

collapsed margin between empty header and nav

Let’s start with this markup which I have oversimplified for the demonstration.

As you can see, we have a nav tag that is enclosed in a header tag which makes the nav a sibling. The blue outline tells us that how the header is rendered. Following are the styles applied,

We can see that there is a gap of 2rem above the Nav Item however that gap should be inside the blue outline. The reason it’s not inside is, the 2rem margin has been collapsed with the parent and that’s why the child element goes outside of its parent. We can see that in the below screenshot

The highlighted section is nav which is appearing outside of the parent.

This is margin collapsing between parent and first or last child element. This was proving to be very difficult to understand and no matter where I went I couldn’t understand this variant of margin collapse.

The way to avoid this is to add padding to header instead, but there are other techniques as well which you can refer to from the article below.

I simply wanted to cover the issue and the reason behind it so that anyone coming across it won’t spend access time understanding it endlessly tweaking the CSS.

I would recommend following this article which covers the entire topic brilliantly. margins-in-css

--

--

Vaibhav Mande
Vaibhav Mande

Written by Vaibhav Mande

I am a Frontend Developer from Montreal, Canada. I write about everything that fascinates me. https://vaibhavmande.com

No responses yet