2

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.

dan1st
  • 12,568
  • 8
  • 34
  • 67
Daft
  • 10,277
  • 15
  • 63
  • 105
  • Floated content removes it from the normal document flow, meaning its container will not stretch to contain the floated content. This is not an "issue", it's just what a float is - modern layout techniques that make heavy use of floats (and clearfixes) are not really what the property was originally intended for. – Ennui Jun 12 '14 at 14:12

2 Answers2

5

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

potashin
  • 44,205
  • 11
  • 83
  • 107
  • 1
    Thanks for the response, but I'm not looking for a fix. I'm looking for an explanation as to why this happens. – Daft Jun 12 '14 at 14:08
3

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

K K
  • 17,794
  • 4
  • 30
  • 39