Margin Collapsing Explained

What you get is not what you coded.

Allen Kim
Digital-Heart
3 min readJul 17, 2020

--

Photo by Suad Kamardeen on Unsplash

As the documentation said, Mozilla Documentation, the top and bottom margins of blocks are sometimes combined (collapsed) into a single margin.

  • The margins of adjacent siblings are collapsed.
  • For empty block, its top and bottom margins collapse

It’s better to see it rather than words.

Example 1

The top/bottom margins of adjacent siblings are collapsed.

From the following example, the margin between box 1 and box 2 is not 36px, which is box 1 bottom margin 12px and box 2 top margin 24px. but it is 24px which is bigger margin between 12px and 24px.

Example 2

If the container does not have any content separating style, e.g. border, padding, margin collapsing will happen to the outside of parent.

The following example has the following code.

We just saw that box1 bottom margin and box2 top margin collapses. How about box2 bottom margin and and box3 top margin which are not sibling? Margin collapsing also happens when the container does not have border or padding.

To see it clearly, following is example of margin collapsing not happening when the container has a blue border.

Example 3

Margin collapsing applies to empty box. The following example has 3 empty box1s, which has 12px top/bottom margin. No matter how many empty boxes are there, no margin applies to empty boxes.

Example 4

Margin collapsing does NOT apply to inline-block;

Example 5

Margin collapsing does NOT apply to flex box.

Here is a code and demo you can experience margin collapsing.

Happy coding :)

This article is a part of Angular Random How-Tos. You may find some useful articles for your daily development.

Do you think this useful? If so please;
*
Clap 👏 button below️ to let others to see this too.
* Follow Allen on Twitter (@allenhwkim)

--

--