块元素会忽略浮动元素吗?

Do block elements ignore floating elements?

W3C states 即:

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.

这与 divs 的预期一样有效:

#a
{
 width: 100px;
 height: 100px;
 background-color: blue;
 float: left;
}

#b
{
 width: 200px;
 height: 200px;
 display: block;
 border: 1px solid black;
 background-color: red;
}
<body>
 <div id=a></div>
 
 <div id=b></div>
</body>
这里红色的 div 是块级元素,因此它忽略了浮动元素。 (如果我把红色的改成 display: inline-block 它会出现在浮动的旁边)

但是,如果我将 display: block 应用于图像,它不会忽略浮动 div,为什么?

#a
{
 width: 100px;
 height: 100px;
 background-color: blue;
 float: left;
}

#b
{
 width: 200px;
 height: 200px;
 display: block;
 border: 1px solid black;
}
<body>
 <div id=a></div>
 
 <img id=b src="https://www.gravatar.com/avatar/5cb44dcd4ebddfea3ede8c6d46b02795?s=328&d=identicon&r=PG&f=1">
</body>

W3C 在查看 W3C 时,这两件事让我印象深刻。 它正在考虑它作为一个线盒。

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.

A line box is next to a float when there exists a vertical position that satisfies all of these four conditions: (a) at or below the top of the line box, (b) at or above the bottom of the line box, (c) below the top margin edge of the float, and (d) above the bottom margin edge of the float.

在你引用的一段之后的几段,规范说:

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.

虽然您已将 display: block 应用到图像,但作为图像,它是一个替换元素,因此浮动不能侵入其边界。

只有未建立块格式化上下文且与浮点数处于同一流中的非替换块框才会忽略浮点数。1 块级替换元素不是块盒,因为替换元素不能是块容器盒。2


1 您可能在想,这是一个荒谬的具体陈述,确实如此。这就是为什么像 "block element" 这样的术语在 CSS 的说法中被认为是极其模糊的。再一次,CSS 本身定义了几乎同样模糊的术语,如 "block box" 来专门指代既是块级框又是块容器框的框,这无济于事。

2 这确实意味着 "non-replaced block box" 在某种程度上是同义反复,它强化了该陈述的具体程度。