I have been running some tests to find out why some CSS margins collapse and why some don’t. I have the following test code:
<div id="seconddiv" style="margin-top:10px; margin-bottom:10px;">
<p style="height:200px; margin-top:5px; margin-bottom:5px;">This is the first paragraph in the second div!This paragraph is 200px tall.</p>
<p style="height:300px; margin-top:5px; margin-bottom:5px;">This is the second paragraph in the second div!This paragraph is 300 px tall.</p>
<p style="height:400px; margin-top:5px; margin-bottom:5px;">This is the third paragraph in the second div!This paragraph is 400px tall.</p>
</div>
I am trying to accurately get the height of the div, but scrollHeight returns “910px”. Why is that? I expected “900px” as the scrollHeight, as it does not include margins.
Did some of the <p> margins collapse and get counted in the height? Why some and not others. I tried many different combinations of margin heights and no values reveal what is going on.
I do not think you’re understanding what “margin-collapse” means.
I’m going to use this simplified markup in the following examples:
HTML:
CSS:
Instead of displaying each margin as separate spacing, top and bottom margins on elements will merge with their sibling (or if no prev/next sibling exists, their parent*) elements so that the spacing between is the largest margin.
If there were no margin collapse, the above markup would appear as:
With margin-collapse, the markup is displaying as:
What this means for the height of the div is that it includes the height of each of its elements and the margins between them.
In my example the height is
100 + 5 + 100 + 5 + 100 = 310.In your example the height is
200 + 5 + 300 + 5 + 400 = 910.* There is some additional complexity involving padding, positioning and floating, which is described by the specification.