【问题标题】:Floating elements causes the parent to collapse. HTML / CSS浮动元素会导致父元素折叠。 HTML / CSS
【发布时间】:2014-08-02 21:35:18
【问题描述】:

如果我有以下代码:

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

父级将折叠并显示为 0px 的高度。

所以我猜这是一个已知问题,有 fixes 可用,但我真的很想知道为什么首先会发生这种情况。

谁能解释一下?

我不是在寻找任何 CSS 修复程序,它们已被 here 覆盖,我正在寻找关于为什么会首先发生这种情况的解释。

【问题讨论】:

  • 浮动内容将其从正常文档流中移除,这意味着其容器不会拉伸以包含浮动内容。这不是一个“问题”,它只是浮​​点数 - 大量使用浮点数(和 clearfixes)的现代布局技术并不是该属性最初的用途。

标签: html css css-float collapse


【解决方案1】:

发生这种情况是因为具有float 属性的元素已从文档流中删除,因此父元素的大小保持未知(因为其中不包含任何内容),因此将其设置为0。使用overflow:auto 调整父级的height 与浮动的内部内容。

your sample vs overflow:auto sample

【讨论】:

  • 感谢您的回复,但我不是在寻找解决方法。我正在寻找关于为什么会发生这种情况的解释。
【解决方案2】:

既然你需要原因,我认为post 解释得很好。除了原因,它也有一些解决方案。

关于浮动:

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 2013-11-27
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2012-03-02
    • 2021-09-22
    相关资源
    最近更新 更多