Floating elements causes the parent to collapse. HTML / CSS

好久不见. 提交于 2019-11-29 16:12:38

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!