How would two empty divs with only margins collapse?
html file:
<div id="div1"></div>
<div id="div2"></div>
CSS File:
#div1 {
margin-top: 10px;
margin-bottom: 20px;
}
#div2 {
margin-top: 10px;
margin-bottom: 30px;
}
Thanks.
Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin.
If there is no border, padding, inline content, height , or min-height to separate a block's margin-top from its margin-bottom , then its top and bottom margins collapse. Some things to note: More complex margin collapsing (of more than two margins) occurs when the above cases are combined.
Margins of elements do not collapse when the value of the overflow property of the elements is set to anything other than visible. Its value must be visible so that margin can collapse.
In CSS2, only vertical margins are specified to collapse — that is the top and bottom margins on an element if you are in a horizontal writing mode. So the left and right margins above are not collapsing and ending up outside the wrapper.
The answer is:
You will have only 30px margin at the end
You are facing two kind of margin collpasing. Since each div is empty, its top margin and bottom margin will collapse so for the first one we will have 20px
and for the second one 30px
. Then those margin will also collapse together and will end with only 30px
.
You can verify this by checking the height of the html element and you will see this:
#div1 {
margin-top: 10px;
margin-bottom: 20px;
}
#div2 {
margin-top: 10px;
margin-bottom: 30px;
}
<div id="div1"></div>
<div id="div2"></div>
From the sepcification:
top and bottom margins of a box that does not establish a new block formatting context and that has zero computed 'min-height', zero or 'auto' computed 'height', and no in-flow children
And
bottom margin of box and top margin of its next in-flow following sibling
As a side note, the body has also a default margin (8px
) collapsing with other other margin following this rule:
top margin of a box and top margin of its first in-flow child
And
bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height
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