Search⌘ K
AI Features

Special Behavior of Margins

Explore the special behaviors of CSS margins, including collapsing margins that combine adjacent spaces, and how negative margins can create unique visual effects. Understand techniques to manage these behaviors by adjusting padding and margin values to achieve desired layout results.

CSS has a feature called collapsing margins where two separate margins become a single margin.

The Listing below shows two situations when this phenomenon occurs.

Listing: Spacing with percentages

<!DOCTYPE html>
<html>
<head>
  <title>Spacing with percentages</title>
  <style>
    body {
      font-family: Verdana, Arial, sans-serif;
    }

    h1 { margin-bottom: 25px; }
    p { margin-top: 20px; }

    #warning {
      border: 2px dotted dimgray;
      padding: 8px;
    }
    h2 { margin: 16px; }
    #head {
      background-color: navy;
      color: white;
    }
    #head p { margin: 16px; }
  </style>
</head>
<body>
  <h1>Heading with margin-bottom: 25</h1>
  <p>Paragraph with margin-top: 20</p>
  <div id="warning">
    <h2>Did you know...</h2>
    <div id="head">
      <p>It is special!</p>
    </div>
    <p>
      Lorem ipsum dolor sit amet, consectetur
      adipiscing elit fusce vel sapien elit
      in malesuada semper mi, id sollicitudin.
    </p>
  </div>
</body>
</html>

According to the style sheet, the <h1> tag has a 25-pixel bottom margin, and the adjacent <p> tag has a 20-pixel top margin. These two are 45-pixels altogether. However, as ...