State of Collapse

Sometimes the most trivial CSS task can yield unexpected results. Here’s what I was trying to do:

Place a div within another div with a top margin. I’ll surround each with an outline. Easy peasy, right?

There are multiple ways to go about this, but I opted for the absolute most trivial one I could think of: use a top-margin on the inner box. Job done. I’ll be collecting my check by tomorrow morning, thank you very much.

Only… Go ahead. Give it a try. I dare you. You know what? I double dare you!

You didn’t see that coming, now did you? Both boxes moved. So, in a sense, the inner box did get pushed down, but it dragged the container with it as well, resulting with the inner one still stuck to the top.

Wth happened? 😨

This, my friends, is margin collapse.

In a nutshell: when two vertical margins of different elements touch, the larger one will be honored. It both makes and doesn’t make sense. You could have assumed it would be the sum of margins, but either way it’s a consistent strategy on deciding what to do with competing margins.

Although you’d be quick to assume the container didn’t have a set margin, it actually did. It’s a block element, so by default it has a margin. Even though 0, it’s still a valid value to be compared against. So obviously the inner margin won the race. Had you tried using a higher value for the container, both would have been pushed down even further. Again, not by the sum, but by the larger of the two – the container’s margin.

The concept of collapsing margins is more complex than this single scenario, and I may cover it in more detail in the future with more examples, but let’s stick to our case. How can we solve this? 🤔

Well, the most important thing to remember, that the container plays a role in this game of margins due to its blocky nature. Change it to something else and you’re good to go, at least with some of the options.

Try it. Change the container’s position to inline-block and see how the issue disappears. Note that this affects the container both internally and externally, so you may wish to specify something different. For example flex and grid would also do the job fine. 💪

Two key takeaways from this:

  • CSS isn’t trivial because responsive design isn’t. HTML elements don’t really lie on a fixed grid like in the days of yore. They relate to one another. This needs consideration and handling.
  • Encountering an issue with such a simple task can be daunting. You can either address it by looking for the solution, or investigate and understand better. This is true for many challenges, not just CSS naturally. I chose the latter.

Don’t let collapsing margins make you collapse. Embrace CSS quirks and grow professionally. 💪💪💪


Leave a Reply

Your email address will not be published. Required fields are marked *