gpt4 book ai didi

css - 相邻 sibling 的边距折叠

转载 作者:行者123 更新时间:2023-12-04 11:23:47 30 4
gpt4 key购买 nike

我正在阅读有关 Margin Collapsing 的文章,我遇到了这个:margin

Adjacent siblings The margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats).



我不明白最后一句话“除非后一个兄弟需要清除 float ”。有人可以举个例子吗?

谢谢

最佳答案

首先,以下示例仅适用于基于 Gecko 的浏览器,例如 Windows 或 Android 上的 Firefox。 Chrome/Webkit 长期以来一直错误地执行清除操作。

我认为该声明是对规范的误解。规范实际上说的是

Two margins are adjoining if and only if:

both belong to in-flow block-level boxes that participate in the same block formatting context and no line boxes, no clearance, no padding and no border separate them



那么是什么导致清除在这里产生影响呢?这不是后一个兄弟的间隙,而是中间元素的间隙。

考虑这个例子。

.container {
overflow:auto;
border:2px solid;
}
span {
float:left;
width:100px;
height:100px;
background:red;
opacity:0.2;
}
.container > div {
height:60px;
margin:20px 0;
background:blue;
}
b {
display:block;
clear:left;
}
<p><strong>View this in Firefox</strong></p>
<div class="container">
<span></span>
<div></div>
<b></b>
<div></div>
</div>


without clearance

在这里我们可以看到第一个 div 的边距框和 float 一样高。 <b>元素不需要向下移动来清除 float ,因此它没有间隙。它也没有内容、内边距、边框或边距,因此第一个 div 的下边距与第二个 div 的上边距折叠在一起。

但是,在这个例子中:

.container {
overflow:auto;
border:2px solid;
}
span {
float:left;
width:100px;
height:100px;
background:red;
opacity:0.2;
}
.container > div {
height:59px;
margin:20px 0;
background:blue;
}
b {
display:block;
clear:left;
}
<p><strong>View this in Firefox</strong></p>
<div class="container">
<span></span>
<div></div>
<b></b>
<div></div>
</div>


with clearance

第一个 div 的边距框比 float 的高度短 1px。于是清除了 <b>元素将其向下移动 - 即它有间隙。现在第一个 div 的底部边距和底部 div 的顶部边距无法折叠,即使元素仍然没有内容、填充、边框或边距并且仅向下移动 1px。

在 Chrome 中, clear:left<b> element 导致边距不折叠,无论它是否有间隙,只有在需要向下移动超过 float 时才应该有间隙。

关于css - 相邻 sibling 的边距折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61232549/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com