Gareth Redfern developer, cyclist & coffee lover

CSS Margin Collapse

Posted by Gareth Redfern
Category: css

The other day I happened to be working on a site where I added margin to both the parent and its child element, only to find that this didn’t behave as I expected. To fully understand what was happening I had to do some digging on the margin collapse rule. We are all familiar with the standard margin collapse rule:

Margins collapse between adjacent elements. In simple terms, this means that for adjacent vertical block-level elements in the normal document flow, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.

This can be shown in the following CodePen:

It was the second part of the margin collapse rule which I had not encountered before (mainly due to the fact that I don’t tend to put margin on parent and child elements, normally I would just apply padding and margin to the parent element).

Collapsing Margins Between Parent and Child Elements

When you have a parent and child whose margins touch e.g. they have no padding or borders between the margins then you will get margin collapse.

This can be shown in the following CodePen:

If you apply padding or a border to the parent container then both margins will be honored:

As I explained the second margin collapse really isn’t something you would come across much as normally you would just apply padding to the parent to achieve the same but without having to add a border or padding to the parent. This article at Sitepoint goes into much more detail if you need a more in-depth explanation.