问题
If I have the following code:
<div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
The parent will collapse and appear to have a height of 0px.
So this is a known issue I guess, and there are fixes available, but I would really like to know WHY it happens in the first place.
Could anyone explain it?
I'm not looking for any CSS fixes, they have been covered here, I'm looking for an explanation as to why this occurs in the first place.
回答1:
Since you needed the reasons, I think this post explains it very well. Apart from reasons, it also has some solutions to tackle it.
About float:
when an element is floated it is taken out of the normal flow of the document.
It is shifted to the left or right until it touches the edge of it's containing
box or another floated element.
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/float
About clear:
The clear CSS property specifies whether an element can be next to floating
elements that precede it or must be moved down (cleared) below them.
The clear property applies to both floating and non-floating elements.
When applied to non-floating blocks, it moves the border edge of the
element down until it is below the margin edge of all relevant floats.
This movement (when it happens) causes margin collapsing not to occur.
When applied to floating elements, it moves the margin edge of the element
below the margin edge of all relevant floats. This affects the position of later
floats, since later floats cannot be positioned higher than earlier ones.
The floats that are relevant to be cleared are the earlier floats within the
same block formatting context.
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clear
回答2:
This happens because elements with float
property are removed from the document flow so the sizes stay unknown for the parent element (as nothing is contained in it) so it is set to 0
. Use overflow:auto
to adjust the parent's height
with the floated inner content.
your sample vs overflow:auto sample
来源:https://stackoverflow.com/questions/24186453/floating-elements-causes-the-parent-to-collapse-html-css