Sobes.tech
Middle

What is margin collapse and what is it used for?

sobes.tech AI

Answer from AI

Margin collapsing is a mechanism in CSS where the vertical margins of two or more adjacent block elements, as well as a parent and its first/last child, do not add up, but instead collapse into a single margin equal to the largest of them.

Collapse occurs in the following cases:

  • Adjacent elements: The margin-bottom of one element and the margin-top of the next element.
  • Parent and first/last child: The parent's margin-top and the first child's margin-top; the parent's margin-bottom and the last child's margin-bottom. This happens if there are no borders, paddings, inline content between them, or if the parent is not a flex/grid container.
  • Empty blocks: The element's margin-top and its margin-bottom if it has no content, borders, or padding.

Example of adjacent elements:

<div style="margin-bottom: 20px;">Element 1</div>
<div style="margin-top: 30px;">Element 2</div>

In this case, the space between the elements will be 30px, not 50px.

Example of parent and first child:

<div style="margin-top: 40px;">
  <div style="margin-top: 30px;">Child element</div>
</div>

The distance from the top edge of the parent to its content will be 40px.

Uses:

Collapse helps maintain predictable vertical spacing between blocks in the normal document flow, preventing excessive gaps. It simplifies creating consistent typographic vertical rhythm, as designers can specify margins for paragraphs or headings independently, and the browser will handle the correct merging of space.

How to prevent collapse:

  • Add a border (border) between elements or between parent and child.
  • Add padding (padding) between elements or between parent and child.
  • Use the overflow property with a value other than visible on the parent element.
  • Use floating elements (float).
  • Use absolute or fixed positioning.
  • Convert elements to a Flexbox or Grid formatting context (on the parent).
  • Make the element inline-block.
/* Preventing for parent and child */
.parent {
  border-top: 1px solid transparent; /* or padding-top */
}
/* Preventing for adjacent elements */
.element + .element {
  margin-top: 0; /* or border-top */
}