Understanding Margin Collapse in the CSS Box Model

css box model mastering margin collapsing
10 November 2024

What is Margin Collapse?

Margin collapse in CSS is one of those phenomena that can sometimes lead to confusion. This phenomenon occurs when two or more adjacent block-level elements with margins overlap. In this case, instead of these margins stacking on top of each other, only the largest of them takes effect.

Practical Tips on Margin Collapse

Imagine two paragraphs that each have a margin. When they are adjacent, instead of increasing the total margin between them, they collapse into the larger margin. Or, the margins of these elements combine and instead of two margins, only one margin is created. This can lead to designs that seem off, especially in some situations where it may cause confusion.

How to Prevent Margin Collapse?

Fortunately, preventing this collapse is also quite easy. One of the methods is to add CSS properties like padding or border to the elements. This action usually leads to breaking the margin collapse and allows us greater control over the spaces between block-level elements.

Special Cases and Exceptions

Keep in mind that margin collapse only occurs for block-level elements and that inline elements maintain their initial spacing. Also, if the elements have CSS properties like float or absolute position, margin collapse will not take place.

A Simple Example of Margin Collapse


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        p {
            margin-top: 20px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <p>First Paragraph</p>
    <p>Second Paragraph</p>
</body>
</html>
  

Line-by-Line Code Explanation

<!DOCTYPE html>: Indicates the document type to the browser.
<html lang="en">: Indicates that the HTML document is in English.
<head>: Contains metadata that will not display in the browser.
<meta charset="UTF-8">: Defines the character set for displaying the document correctly.
<meta name="viewport" content="width=device-width, initial-scale=1.0">: Adapts the page for different devices.
<style>...</style>: Contains the CSS styles for the document.
p { margin-top: 20px; margin-bottom: 20px; }: Sets margins for paragraphs.
<body>: The main body of the HTML document that contains the content.
<p>First Paragraph</p>: Displays the first paragraph.
<p>Second Paragraph</p>: Displays the second paragraph.
</body>: Ends the body section of the HTML document.

FAQ

?

How can I prevent margin collapse?

?

Does margin collapse affect inline elements as well?

?

For which elements does margin collapse not happen?