html - 为什么 float 元素不会挤压行内元素?

标签 html css css-float

我正在尝试研究 css float 的行为。这是有线的东西:JSFiddle .我有一个容器,一个内联 span 和两个 float p:

<div id="box1">
    <span>Box 1</span>
    <p id="p1">Paragraph 1</p>
    <p id="p2">Paragraph 2</p>
</div>

如果 span 不存在,p1p2 将在同一行。但是,当 p1span 向右挤压时,p2 被放入下一行!

按我的理解,p2应该放在p1的右边,span应该往下挤到下一行。我检查了 Spec但找不到原因。 (好吧,也许我没看懂规范)。

这是什么原因?

最佳答案

通常,如果没有宽度限制,#p1#p2 会随着 span 出现在 旁边 float >#p2.

但是因为 span 在标记中首先出现,然后是 float 元素,这意味着 span 需要定位得尽可能高,然后是 float 元素沿与 span 相同的行(以及必要时的后续行)。该行在规范中称为“当前行”。以下是您链接到的部分的相关引述:

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

A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the outer top of the floated box is aligned with the top of the current line box.

Any content in the current line before a floated box is reflowed in the same line on the other side of the float. In other words, if inline-level boxes are placed on the line before a left float is encountered that fits in the remaining line box space, the left float is placed on that line, aligned with the top of the line box, and then the inline-level boxes already on the line are moved accordingly to the right of the float (the right being the other side of the left float) and vice versa for rtl and right floats.

由于没有足够的空间在同一行包含 float span,这迫使 #p2 被推送到下一行,因为只有足够的空间容纳第一行的 #p1span

如果容器足够宽,您会看到两个 float 都将出现在与 span 相同的行上。这里的关键是 span 必须尽可能高,因为它出现在 float 之前,然后 float 可能不会更高(这在 section 9.5.1 中提到):

  1. The outer top of an element's floating box may not be higher than the top of any line-box containing a box generated by an element earlier in the source document.

或者,如果您将 span 移动到容器的末尾,如下所示:

<div id="box1">
    <p id="p1">Paragraph 1</p>
    <p id="p2">Paragraph 2</p>
    <span>Box 1</span>
</div>

然后 float 将首先出现,span 移动到下一行,因为没有足够的空间将其与 float 放在同一行。

关于html - 为什么 float 元素不会挤压行内元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27292404/

相关文章:

javascript - 使用 Javascript 以用户身份提交具有多个提交按钮的表单

java - 不要在 JLabel 中使用 XML 文件读取 '&lt;'

css - div 中的文本和图像 - 如何正确对齐?

ios - 使用百分比和像素时,Calc 在 iOS 11.2.1 safari 上不起作用

html - 我如何将底部移动到其他标题和段落的右侧

c++ - 如何在 CGI 应用程序中解析 HTML 文件并修改其内容? C++

jquery - 使用 jquery 将值从一个页面传递到另一个页面

html - 由于调整大小而发生换行时如何强制 float DIV 使用最大水平空间

html - Unruly CSS 伪元素框阴影

css - 使外部div自动与其 float 内容相同的高度