css - 为什么css float不会改变后面div的宽度?

标签 css css-float

据我所知,float:left 会将后续元素推到其左侧,而不是换行。

在下面的示例中,我希望第二个 div 从第一个 div 的右侧开始,但正如您在下面的 jsfiddle 中看到的那样,它仍然跨越整个宽度。

另一方面,内容神奇地从它应该出现的地方开始。 float 规则是否只 float 内容而不 float 边距?

Example here

.inline {
    float:left;
}

.yellow {
    background-color:yellow;
}
<div class="inline">
    first line<br>
    second line<br>
    third line<br>
</div>

<div class="yellow" >floated div</div>

编辑:我希望上面的代码看起来像 like this 但没有明确需要使用边距。

最佳答案

这是 float 定位的预期行为。

当一个元素向左浮动时(在你的例子中是.inline div),下面的内容会流到该元素的右侧,行框会变短但是containing block 的宽度会变小由以下元素(在您的例子中为 .yellow div)建立的 reserved

这在规范中有记录:

9.5 Floats

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 级元素(例如 <div><p> ,...)——没有定位——忽略 float ,而线框沿着它的边流动。

W3C给出的例子:

CSS float overlapping [D]

The IMG box is floated to the left. The content that follows is formatted to the right of the float, starting on the same line as the float. The line boxes to the right of the float are shortened due to the float's presence, but resume their "normal" width (that of the containing block established by the P element) after the float.

因此,如果您给出 .yellow元素背景,您会看到它跨越容器并继续通过 float 元素。

解决方案

来自 CSS level 2.1 spec :

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.

因此,如果您添加 overflow值(value)不是 visible 的属性(property)到 .yellow div,它可以防止 div 与 float 元素重叠:

EXAMPLE HERE

.yellow {
    overflow: hidden;
}

重叠在 length of the following content is large enough 的情况下特别有意义在 float 元素之后正常继续。

如果默认限制,the content wouldn't be continued在 float 元素下。

关于css - 为什么css float不会改变后面div的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25475822/

相关文章:

javascript - 弹出窗口打开时在后台禁用所有内容

css - 使内容适应窗口高度

html - 使用 <ul> 时 3 列布局无法正确显示

jquery - 我正在尝试将我的文本值与 slider 栏对齐,但遇到问题

具有许多嵌套和 float Div 的 CSS 100% 高度

html - 位置固定宽度 100%

html - DIV 使用 JQuery 淡入滚动,但不会在每个像素上触发

html - 如何将文本环绕在右下角的 div 周围?

css - Chrome 浏览器 - 绝对定位和 float 问题

css - 将 div 置于两个 float 之间的问题