Cyrus Yip's blog

What is Margin Collapsing in CSS

Cyrus Yip

Margin collapsing is a feature in the flow layout. When an block element comes after another block elements, the bottom margin of the upper element and the top margin of the lower element collapse (merge into a single margin). The larger margin remains, and the smaller margin disappears. If the two margins are equal, one of them remains. Margins don’t collapse in a flex container or a grid container.

Example (live preview):

1
2
3
4
5
<!-- Margin collapsing example -->
<div class="container">
  <p class="upper">Upper element</p>
  <p class="lower">Lower element</p>
</div>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
p {
  /* Remove default margins */
  margin: 0;
}

.upper {
  /* Larger margin remains */
  margin-block-end: 50px;
}

.lower {
  /* Smaller margin disappears */
  margin-block-start: 10px;
}

.container {
  border: 1px solid purple;
  /* Margins don't collapse in the flex layout or grid layout */
  /* display: grid; */
}

p {
  border: 1px solid green;
}

The bottom margin of the upper element (50px) is larger, so it remains and another margin (10px) disappears. When we add display: grid; to the container, <p> elements become grid items, which establish block formatting contexts, so margin collapsing is disabled. Now you can see the two margins exist at the same time.

For more details on block formatting context, see What is Block Formatting Context (BFC) in CSS.


Further reading: Mastering margin collapsing - CSS: Cascading Style Sheets | MDN

Tags: