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.
Quoting from W3C: In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin. Margins of the root element's box do not collapse.
In CSS, adjacent margins can sometimes overlap. This is known as “margin collapse”, and it has a reputation for being quite dastardly. This is an interactive element! Instead of sitting 48px apart, their 24px margins merge together, occupying the same space!
The CSS margin properties are used to create space around elements, outside of any defined borders. With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With