While working on my new theme for this site I ran into a problem: CSS collapsing margins.
Well, from the beginning let me be very clear: this will not be a comprehensive article on this subject. There is already one written by Josh Comeau and is excellent: “The Rules of Margin Collapse“. I urge you to go for that if you want to get all the ins and outs of that matter. For me it was an eye opener.
It turns out that I had taken it wrongly how margins work. Margin is meant to increase the distance between siblings. It is not meant to increase the gap between a child and its parent’s bounding box; that’s what padding is for. See how I coded that initially (in SASS):
.navigation { /* p { margin: 20px 15px; } */ width: inherit; //overflow: auto; margin: 40px 40px; & p > a { ... etc
And the result was:
However, adding padding will do the trick. This is because padding is intended to define space between parent and children elements. Changing code and adding padding:
.navigation { /* p { margin: 20px 15px; } */ width: inherit; //overflow: auto; margin: 40px 40px; padding: 20px 40px; & p > a { ... etc
Will render correct spacing:
.navigation { /* p { margin: 20px 15px; } */ width: inherit; overflow: auto; margin: 40px 40px; ... etc
Adding overflow
will also fix the issue. This is because the overflow property creates a scroll container, and margins can’t collapse across scroll container boundaries. As a general conclusion, margins must be touching in order for them to collapse. Any gap between margins (including a scroll container created by overflow
keyword) will prevent margins’ collapse.
FYI, the inherit
CSS keyword causes the element to take the computed value of the property from its parent element.
Leave a Reply