css - 为什么未 float 的 div 会覆盖/重叠 float 的 div? (以 "why"为焦点)

标签 css css-float

我的问题涉及何时有一个 div float (float:left) 并且其后的 div 没有 float 。在那种情况下,为什么未 float 的 div 会覆盖并重叠第一个 div?这就像第一个 float 的 div 从流中取出(如绝对定位),第二个未 float 的 div 如何越过第一个 div。

我知道第二个未 float 的 div 中的文本不会这样做。它似乎知道第一个 div 并漂浮在它旁边。

我也知道解决方法是让第二个 div 也向左浮动。

我的问题侧重于为什么。为什么第二个未 float 的 div(除了其中可能包含的任何文本)覆盖并重叠第一个 float 的 div?

在 Stack Overflow 上的另一个类似问题中,有人说“ float 从正常流中删除一个元素,这意味着相邻元素的定位就像 float 不存在一样......如果元素不是这种情况有一个内联显示。”所以我的问题是为什么从正常流中移除 float 元素(内联元素除外)?我理解为什么内联元素会出现这种情况(例如,您希望将文本刷新到 float div 以在图像周围自动换行)。但是为什么它完全从正常流程中删除了???

下面是一些代码来说明我的意思。

.box1 {
  border: solid 3px;
  width: 350px;
  float: left;
  height: 100px;
}
.box2 {
  background-color: lightblue;
  width: 400px;
  height: 150px;
  border: blue solid 3px;
}
<div>
  <div class="box1"></div>
  <div class="box2"></div>
</div>

最佳答案

It's like the first, floated div is taken out of the flow

没错,就是这个原因。 float 元素是 out-of-flow :

An element is called out of flow if it is floated, absolutely positioned, or is the root element.

考虑到 floats 的行为,这是必要的:

A float is a box that is shifted to the left or right on the current line.

如果它们没有从正常流中移除,它们将在移动之前继续占据其初始位置的一些空间。

注意内联 float 也不异常(exception),因为没有这样的东西。如 Relationships between 'display', 'position', and 'float' 中所述, float 被 block 化

因此, float block 后面的 block 与它重叠:

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

您可以通过建立一个新的 block 格式化上下文来防止这种行为:

The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap the margin box of any floats in the same block formatting context as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space.

.box1 {
  border: solid 3px;
  width: 350px;
  float: left;
  height: 100px;
}
.box2 {
  background-color: lightblue;
  width: 400px;
  height: 150px;
  border: blue solid 3px;
  overflow: hidden; /* Establish BFC */
}
<div>
  <div class="box1"></div>
  <div class="box2"></div>
</div>

关于css - 为什么未 float 的 div 会覆盖/重叠 float 的 div? (以 "why"为焦点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213248/

相关文章:

html - 如何修复最大宽度和 float :left interaction

css - 滚动 CSS Floats 而不是中断

css - 动态高度后 float

javascript - 使用 CSS : How to auto layout events 创建日历控件

html - asp.CheckBox 渲染显示在跨度内。样式属性以跨度结束,而不是复选框

html - 去除html页面中的颜色

CSS:单行动态宽度文本的左对齐文本中的省略号,其中左对齐文本的宽度 = 100% - 右对齐文本

css - 向右浮动不会在向左浮动元素的情况下一直向上 float

html - 从 :before pseudo element 清除动画

html - 嵌套 flexbox 优化