Simple CSS question, I’ve been wondering for a while and I’d like to understand exactly how this works.
Let’s say I have the following:
<div>
<p>some text</p>
<p style="float: left">some text</p>
</div>
If I remove the float: left from a given <p> element, the element and its previous sibling are stacked closer.
Why floating an element causes this increased margin at its top?
The reason for the difference is a behaviour known as collapsing margins.
Note that paragraphs have, by default, a user-agent defined top and bottom margin.
When the second paragraph does not have
float: left, the bottom margin of the first paragraph and the top margin of the second paragraph are adjoining and so collapse into each other.When the second paragraph has
float: left, those two margins will no longer collapse into each other; they are no longer considered adjoining because:Following the “block formatting context” link reveals that:
The spec goes on to say: