微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – 为什么溢出:隐藏有高度增长的意想不到的副作用来包含浮动元素?

这个问题最好由 this fiddle解释,并附有以下HTML:
<div class="outer">
    <div class="inner-left"></div>
    <div class="inner-right"></div>
</div>

CSS:

.outer {
    width: 100px;
    border: solid 5px #000;
}
.inner-left {
    float: left;
    height: 200px;
    width: 50px;
    background: #f00;
}
.inner-right {
    float: right;
    height: 200px;
    width: 50px;
    background: #0f0;
}

基本上,我想知道为什么溢出:隐藏导致外部元素在高度上增长,包含两个浮动元素?

解决方法

最简单的说,是因为一个不可见的溢出块(认值)创建一个新的 block formatting context

创建新的块格式化上下文的框定义为stretch to contain their floats by height,如果它们自己没有指定的高度,认为auto(规范称这些框为块格式化上下文根):

10.6.7 ‘Auto’ heights for block formatting context roots

In certain cases (see,e.g.,sections 10.6.4 and 10.6.6 above),the height of an element that establishes a block formatting context is computed as follows:

[…]

In addition,if the element has any floating descendants whose bottom margin edge is below the element’s bottom content edge,then the height is increased to include those edges. Only floats that participate in this block formatting context are taken into account,floats inside absolutely positioned descendants or other floats are not.

在原始CSS2规范中并非如此,但是作为CSS2.1的一个改变,引入了另一个(而且更为迫切的)问题。 This answer提供了更改的说明。因此,尽管这些变化是非常有意义的,但似乎很容易称之为副作用。

还要注意,这不是清理浮动(清除)一样的事情。只有当您使用清除属性并且有以前的浮动才能被清除时才会清除浮动:

>如果你有一个清楚的元素:这两个都是你的例子中外部元素的兄弟,浮动将被清除,但外部元素不会拉伸。>如果你有一个与外部元素的最后一个子元素(或伪元素)相似的元素(或伪元素)(使其成为浮点的下一个兄弟节点),则外部元素将向下延伸以包含该元素的底部边缘,并且对于零高度元件,其基本上是指浮子的最底边缘。该技术被称为“clearfix”,因为元素(或伪元素)没有其他目的,而不是强制外部元素通过其中的间隙来包含浮点。

原文地址:https://www.jb51.cc/css/219905.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。