26

CSS margin collapsing – what it is and why should I care

 3 years ago
source link: http://www.js-craft.io/blog/css-margin-collapsing-what-it-is-why-should-i-care/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In CSS margin-collapsing refers to the fact that the margins that are next to each other are colliding… but only vertically.

Yeah, it's one of those brainfuck moments in CSS.

Let's first take two divs that are one next to each other on the horizontal axis. If we have a margin: 25px for both divs, and the width: 100px then, as expected, the required width will be 300px.

6VVNNzu.png!web

However, if we try to do the same with the divs are arranged vertically then the total needed space will be 275px, instead of the expected 300px.

nA3umim.png!web

And this is because the vertical margins of the elements are collapsing.

But, what if the margins are of different sizes? What if one div has margin: 25px and the other has a margin: 40px? Well, in this case just the largest of the two margins will be applied (40px in our case).

And what about negative margins? The rule will be applied when both margins are negative (vertically), but not when one margin is negative and the other is positive.

If you want to learn more take you can a look at:

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK