Why would margin not be contained by parent element?

This is how CSS works according to W3C:

In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding, or border areas, or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.

More specific to your case of the top div:

If the top and bottom margins of a box are adjoining, then it is possible for margins to collapse through it. In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed.

  • If the element’s margins are collapsed with its parent’s top margin, the top border edge of the box is defined to be the same as the parent’s.
  • Otherwise, either the element’s parent is not taking part in the margin collapsing, or only the parent’s bottom margin is involved. The position of the element’s top border edge is the same as it would have been if the element had a non-zero bottom border.

The best thing I can do is point you to on “Collapsing Margins” on sitepoint (by Tommy Olsson and Paul O’Brien). They do a very detailed explanation with examples showing you exactly the behaviors you demoed in the question example code.

Leave a Comment