我正在尝试研究 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
不存在,p1
和 p2
将在同一行。但是,当 p1
将 span
向右挤压时,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
被推送到下一行,因为只有足够的空间容纳第一行的 #p1
和 span
。
如果容器足够宽,您会看到两个 float 都将出现在与 span
相同的行上。这里的关键是 span
必须尽可能高,因为它出现在 float 之前,然后 float 可能不会更高(这在 section 9.5.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/