What collapsing margins are, how they work and when margins do not collapse
What collapsing margins are
Imagine you have 2 HTML boxes. The first one has a
margin-bottom of let's say
30px and the second one a
20px. After rules of collapsing margins have been applied we have a margin of
50px) between these two boxes (see this article for an illustration) . This is because no addition of both margins takes place but the maximum of both is applied. This behavior is called collapsing margins and does only apply to vertical margins.
Oftentimes it is a good behavior but collapsing margins can be annoying, too. For example child elements with margins also collapse with margins of the previous sibling of the parent box.
Nevertheless there are some exceptions where the behavior of vertical collapsing margins is not used.
Exceptions when margins do not collapse
Be aware that in some situations, margins do not collapse and we talk about Uncollapsing Margins. The list below summarizes the conditions when margins do not collapse. It is an excerpt from Sitepoint - Collapsing Margins.
- flexbox children
- absolutely positioned elements
- inline-block elements
- elements with overflow set to anything other than visible (They do not collapse margins with their children.)
- floated elements
- cleared elements (They do not collapse their top margins with their parent block’s bottom margin.)
- the root element
Workaround when you absolutely need margins to collapse
When your margins don't collapse due to one of the rules above, you can sometimes use this hack to fix it:
Say you have a tile grid with many 150*150 pixel tiles. Each tile has 10px margin on all sides. When you implement this by letting tiles float left, this 10px margins won't collapse with elements above or below the grid:
.tiles +clear_after .tile float: left height: 150px width: 150px margin: 10px // uncollapsable margin because this floated element will be cleared by its container
What you can do now is to wrap all tiles in another container (
.tiles_inner) which clears the floats and neutralizes the outer tiles' margins with a negative margins. Now we reapply the outer tiles' margin to the outer container (
.tiles). Since no floating is involved, this margin can now collapse properly:
.tiles margin: 10px // this margin can be collapsed .tiles_inner +clear_after margin: -10px // neutralize the margin that cannot be collapsed .tile float: left height: 150px width: 150px margin: 10px // uncollapsable margin because this floated element will be cleared by its container
You can only use this hack if the container knows the margin of its children.
Please follow the links if you want to delve deeper into the subject.