首页>Program>source

我在网页上遇到的一个常见问题是浮动div爬到了其容器之外。

#wrapper{
    border:1px solid red;
}
#wrapper div{
    float:left;
    font-size: 3em;
}
...
<div id="wrapper">
    <div>Hello World</div>
</div>

实时示例:http://jsfiddle.net/ugUVa/1/

有很多方法可以解决此问题(将div插入clear:both)

我看到的一个更整洁的解决方案是将包装器divs溢出样式设置为隐藏:

示例:http://jsfiddle.net/ugUVa/2/

这在所有浏览器上都能很好地工作,并且干净利落,没有其他标记.我很高兴,但我不知道为什么会起作用!

我看过的所有文档都表明存在溢出:隐藏是为了隐藏内容,而不是调整父级的大小以适合其子级...

有人可以对此行为提供解释吗?

谢谢

最新回答
  • 2021-1-12
    1 #

    它将创建一个块格式化上下文。

    Block formatting contexts are important for the positioning (see float) and clearing (see clear) of floats. The rules for positioning and clearing of floats apply only to things within the same block formatting context. Floats do not affect the layout of things in other block formatting contexts, and clear only clears past floats in the same block formatting context.

    另请参见:http://www.w3.org/TR/CSS2/visuren.html#block-formatting

  • 2021-1-12
    2 #

    这是正确的, 样式旨在控制内容溢出的后果。

    对浮动元素的影响是 overflow的副作用 样式创建元素的块格式设置上下文。

    当您不为包含元素指定大小时,块格式化上下文会从其包含的元素中获取其大小,即包含元素所获取的大小。

    overflow

  • winforms:如何在C#中向UserControl添加事件?
  • android:所有屏幕设备的图像尺寸