Home > Article > Web Front-end > 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:
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:
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!