Reputation: 50137
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?
Upvotes: 2
Views: 1141
Reputation: 228302
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:
Two margins are adjoining if and only if:
- both belong to in-flow block-level boxes that participate in the same block formatting context
- [...]
Following the "block formatting context" link reveals that:
Floats [...] establish new block formatting contexts for their contents.
The spec goes on to say:
Note the above rules imply that:
- Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
- [...]
Upvotes: 6
Reputation: 1761
This doesn't occur for me on Chrome19.. but this would occur because of your browser's default stylesheet. If you want to prevent against this happening, use margin: 0; padding: 0; on the floated element.
Upvotes: 0