Home  >  Article  >  Web Front-end  >  How Do Nested Margins Collapse and When Do They Avoid Collapsing?

How Do Nested Margins Collapse and When Do They Avoid Collapsing?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 07:23:02508browse

How Do Nested Margins Collapse and When Do They Avoid Collapsing?

Understanding Nested Vertical Margin Collapse

Many developers struggle with the concept of vertical margin collapse in nested elements. Let's simplify this concept for beginners.

Imagine two nested divs:

<div style="margin-top:10px">
<div style="margin-top:20px">
A
</div>
</div> 

Initially, the inner div's 20px margin takes precedence. However, there are two key rules to remember:

1. Collapse on Touch:
If the margins of adjacent elements touch, they collapse.

2. Nesting Snuggle:
If only a margin separates nested elements, the inner element will "snuggle" against the outer element.

Applying these rules to our example:

  • The margins of the nested divs touch, triggering a margin collapse.
  • The inner div snuggles against the outer div's top edge, despite having a larger margin.

Thus, the overall block applies the maximum of the collapsing margins (20px) to the entire div.

Exceptions to the Collapse:

However, the margin collapse behavior changes if:

  • There's a border or padding between the elements.
  • The inner element is not truly nested (e.g., it's floated or positioned absolutely).

Example of No Collapse:

Adding a non-breaking white space (or border) separates the margins, preventing collapse:

<div id="outer"> 
<div id="inner">
A
</div>
</div>

In this case, the inner div's margin (20px) is applied to its own space, and the outer div's margin (10px) applies to the surrounding area.

By understanding these rules and exceptions, you can now effectively control the spacing of elements with nested margins.

The above is the detailed content of How Do Nested Margins Collapse and When Do They Avoid Collapsing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn