Reputation: 7180
Let's assume that we have the following code:
<div style="margin-bottom:100px;">test</div>
<div style="margin-top:100px;">test</div>
I noticed that sometimes it creates 100px of margin between elements and sometimes it's 200px (when we use certain settings that I'm not familiar with). I can't find any information about that in the specification. What does this depend on?
If we have h1
and p
in a blank document then the margin of h1
will be combined with the margin of p
. They will not add up. Whichever is larger will be used.
Upvotes: 20
Views: 9904
Reputation: 1228
This is happening because your margins are allowed to collapse. Certain margins may overlap (mostly block elements) and form a combined margin defined by the larger of the two values defined in the computed element style rules - that's what is happening here. This section from the CSS Box Model document explains it in detail.
Edit: As a point of interest, you can get around this (ie. break the collapsible margins) without breaking things (much?)in a couple of ways
width: 100%; display: inline-block
height: 0; width: 0; overflow: hidden
block in between the elements and putting a dot or something in it.I forked ashley's fiddle to demonstrate. There are probably other methods but these are a quick a dirty way to get around collapsible margins if you need to.
Upvotes: 21