Collapsing Margin between parent and child

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Todo App Tutorial — Front-end Development

Use JavaScript to Create a Screen Tap Controlled Background Changing Lens in Lens Studio

Using cookies to speed up Puppeteer and Playwright scripts

Component lifecycle phases

Array Destructuring in JavaScript

Ins & Outs of JavaScript — The story of Ecmascript and Harmony

Next.js — The React Framework for Production(Intro)

NeutralinoJS: an native cross platform application development framework.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vaibhav Mande

Vaibhav Mande

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

More from Medium

Have you wondered about Website Accessibility testing?

Enabling Windows 11’s New Redesigned App Picker

How to Set Up a Calculator Form on Your WordPress Website — A Complete Guide With Examples

Make APP UI in Sketch and export various images needed by different OS device and mobile resolution…