CSS Margin Collapse

When two vertical margins meet, they may merge into a single margin that’s equal to the larger of the two. This is known as margin collapse. It often occurs between block-level elements, such as two consecutive paragraphs. Understanding margin collapse helps avoid unexpected spacing issues and ensures a consistent layout.

Key Topics

How Margin Collapse Happens

If a bottom margin of one element touches the top margin of the next, instead of adding them together, the browser uses the larger margin. This prevents double spacing between elements.

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8" >
    <meta name="viewport" content="width=device-width, initial-scale=1.0" >
    <title>Margin Collapse Example</title>
    <style>
        p {
            margin: 20px 0;
            font-family: Arial, sans-serif;
        }
    </style>
</head>
<body>
    <p>Paragraph 1 - Has a 20px bottom margin.</p>
    <p>Paragraph 2 - Also has a 20px top margin, but both will collapse into a single 20px margin, not 40px.</p>
</body>
</html>

Explanation: Instead of a total of 40px between the paragraphs, the margin collapses to 20px, keeping the spacing consistent and not doubled.

Avoiding Unwanted Collapses

Placing elements like padding, borders, or inline-block wrappers between elements prevents margin collapse. For example, if you wrap paragraphs in a container with padding, margins won’t collapse between them and the container.

Key Takeaways

  • Consolidation: Adjacent vertical margins collapse into a single margin.
  • Simplification: This behavior prevents overly large gaps.
  • Control: Adding borders, padding, or changing display can prevent unwanted collapsing.