What is Margin Collapsing in CSS
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):
|
|
|
|
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
comments powered by Disqus