"clear:both" 和 "overflow:hidden" 是否以相同的方式使容器包装浮动 children?

Do "clear:both" and "overflow:hidden" work the same way to make a container wrap floated children?

我有一个 div 浮动 children。

我知道我可以通过以下两种方式拉伸身高:

.container {
  border: 2px solid #ccc;
  margin-bottom: 250px;
}

.container-2::after {
  content: '';
  display: block;
  height: 0;
  font-size: 0;
  clear: both;
}

.container-3 {
  overflow: hidden;
}

.item {
  float: left;
  width: 200px;
  height: 50px;
  background: red;
  margin: 10px;
}
<div class="container container-1">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="container container-2">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="container container-3">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

但我觉得他们有不同的原则:clear:both ::after 元素远离浮动兄弟,并强制 parent div拉伸高度; overflow:hidden 样式使 div 具有 BFC,并且根据 standard,BFC 将拉伸其高度以包括其浮动 children.

优点和缺点并不重要,重要的是它们如何工作。

我说的对吗,它们不同但结果相同?

Do clear:both and overflow:hidden work the same way to make a container wrap floated children?

没有。它们执行不同的功能。

clear:both

clear 属性 控制元素是否可以位于其之前的浮动元素旁边或下方。它控制一个元素是否可以清除浮动的元素。

clear:both,应用于非浮动块级元素时:

Requires that the top border edge of the box be below the bottom outer edge of any right-floating and left-floating boxes that resulted from elements earlier in the source document.

source: https://www.w3.org/TR/CSS2/visuren.html#propdef-clear

所以 clear 属性 更可能适用于浮动元素的兄弟。它与 拉伸具有浮动子项 的 div 的高度无关(如您的问题所述)。

overflow:hidden(或overflow:auto)

overflow 属性 与 visible 以外的值一起使用时,会创建一个新的 block formatting context。这会导致包含浮动的元素扩展以包含其浮动的子元素。

总而言之,属性 清除浮动元素之后的元素。另一个拉伸容器以包裹浮动元素。两者的输出可能看起来相同。但是每个 属性 都是根本不同的。

延伸阅读: