Margin Collapsing Mysteries

Mystery machine margin collapsing meme

come on gang, lets solve some margin collapsing mysteries

Example 1

Example 1 below has a DOM structure like this:

<div>
	<!-- Blue dotted outline -->
	<div class="parent-parent">
	
		<!-- Orange dashed outline -->
		<div class="parent">
			<!-- Red square -->
			<div>e-1</div>
			
			<!-- Blue square -->
			<div>e-2</div>
		</div>
	
	</div>
</div>

Play with the margins to see how they "collapse" (only the largest margin is used, smaller margins are ignored). The margins are represented by 6 tall bars with arrows. In this demos starting position only 3 margin bars create vertical space (the other 3 are "collapsed"). Note that e-1 margin top "collapses" through two levels of parents and pushes on the top of the grey dashed frame:

📱📱open in tab and rotate phone
open in tab ↗

Example 2

Example 2 has a DOM structure like this:

<div class="a">
	<div class="b">
		<div class="c">
		
		</div>
	</div>
</div>

This example shows top margin collapsing on nested elements. Collapsing can be prevented by text elements taking up vertical space between two top margins (the top element boundaries no longer touch so margin collapsing is not activated). The same rules apply to bottom margin collapsing.

📱📱open in tab and rotate phone
open in tab ↗