Collapsing Margin between parent and child
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.
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