Skip to main content

How to deal with margin collapsing?

ยท 2 min read

For example, take two sibling div blocks, one div with a bottom margin of 100px and the other div with a top margin of 50px, What do you think the distance between them is? You might think it will be 100px + 50px = 150px? but it's actually 100px.

<div style="height: 50px; border: 1px solid #afafaf; margin-bottom: 100px;">button margin 100px</div>
<div style="height: 50px; border: 1px solid #afafaf; margin-top: 50px;">top margin 50px</div>
button margin 100px
top margin 50px

We find that between these two elements, their margin-bottom and margin-top are merged and display larger values. This phenomenon is known as margin collapsing. The solution is to create a BFC (Block Formatting Context).

What is BFC?โ€‹

BFC is a technique that allows us to create a block formatting context.

A block formatting context is a part of a visual CSS rendering of a web page. It's the region in which the layout of block boxes occurs and in which floats interact with other elements.

How to create a BFC?โ€‹

  • float property value isleft/right
  • overflow property value is hidden / scroll / auto
  • position property value is absolute / fixed
  • display property value is inline-block / table-cell / table-caption

The above four are very common methods. There are other unusual ways you can refer to this article.

Solve the above problemsโ€‹

now we can solve the above problems with BFC.

<div style="overflow: hidden;">
<div style="height: 50px; border: 1px solid #afafaf; margin-tottom: 100px;">button margin 100px</div>
</div>
<div style="height: 50px; border: 1px solid #afafaf; margin-top: 50px;">top margin 50px</div>
button margin 100px
top margin 50px

you can see now two div blocks margin distance is 150px;