view raw
Daft Daft - 6 months ago 31
CSS Question

Floating elements causes the parent to collapse. HTML / CSS

If I have the following code:

<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</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.


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.


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.