浮动元素会导致父级合拢。 HTML / CSS [英] Floating elements causes the parent to collapse. HTML / CSS

查看:125
本文介绍了浮动元素会导致父级合拢。 HTML / CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

<div>
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>

父项将折叠并显示为高度为0像素。

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.

我不是在寻找任何CSS修正,他们已被覆盖这里,我正在寻找一个解释为什么这种情况发生在第一。 / strong>

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.

推荐答案

由于你需要原因,我认为这个 post 解释得很好。

Since you needed the reasons, I think this post explains it very well. Apart from reasons, it also has some solutions to tackle it.

关于浮动:

 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.

参考: https://developer.mozilla.org/en-US/docs/Web/CSS/float

关于清除:

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.

参考: https://developer.mozilla.org/en-US/docs/Web/CSS/clear

这篇关于浮动元素会导致父级合拢。 HTML / CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆