html - block 元素会忽略 float 元素吗?

标签 html css css-float

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 是 block 级元素,因此它忽略了 float 元素。 (如果我将红色的更改为 display: inline-block 它会出现在 float 的旁边)

但是,如果我将 display: block 应用于图像,它不会忽略 float 的 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>

最佳答案

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

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 应用于您的图像,但作为图像,它是一个替换元素,因此 float 不能侵入其边界。

只有不建立 block 格式上下文并且与 float 在同一流中的非替换 block 框可以忽略 float 。1 block 级替换元素不是 block 框, 因为被替换的元素不能是 block 容器框。2


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

2 这确实暗示“未替换的 block 框”在某种程度上是一种重言式,它强化了该声明的具体程度。

关于html - block 元素会忽略 float 元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829953/

相关文章:

javascript - Android CSS spritesheet webkit 转换和动画的问题

Javascript - 为什么我不能将 style.color 设置为变量?

css - 我可以使用 calc 和 var 根据宽度更改我的 div 高度吗?

html - css - 清除两者后差距很大

jQuery 绑定(bind)元素可见性与条件

javascript - 如何检测html输入对象是否是按钮?

javascript - 适合对象 : get resulting dimensions

javascript - 如何将日期选择器应用于下拉列表

CSS Floated div 出现在父 div 下面

html - 导航菜单消失