float:left 段后接 float:none 段

float:left paragraph followed by float:none paragraph

我试图理解浮动行为,所以我在下面写了简单的两段。

第二段float:none出现在"contain/surround"第一段float:left。

谁能帮我理解这是为什么。

<p style="float:left; border:red solid 1px;">
  first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph.
</p>

<p style="float:none; border:green solid 1px;">
  second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph.</p>

顾名思义,元素是浮动的,因此您必须清除元素,以便它们以您想要的顺序出现。

设置了清除 属性 的元素不会像浮动所希望的那样向上移动到浮动附近,而是会向下移动超过浮动。同样,插图可能比文字更有效。

此信息来自 here,这将有助于更好地解释浮动。

浮动元素之后的元素会围绕它流动。 浮动元素之前的元素不会受到影响。

如果你想让 HTML 流量再次正常,你需要清除它: css-clear

第一段是浮动的 taken out of the flow,而第二段保持流动状态,因此第二段的方框的位置就像第一段不存在一样。

但是,第二段中的文本被第一段压低了,因此它仍然可见。这样做的技术原因是文本是内联内容,沿着一组行框流动。来自 spec:

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.

[...]

If a shortened line box is too small to contain any content, then the line box is shifted downward (and its width recomputed) until either some content fits or there are no more floats present.

由于文本被下推,这导致第二个段落框的边界也向下延伸,以适应文本的新位置。

如其他答案中所述,通常通过清除浮动来防止此行为:

<p style="float:left; border:red solid 1px;">
  first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph. first paragraph.
</p>

<p style="clear:both; float:none; border:green solid 1px;">
  second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph. second paragraph.</p>