外边距塌陷之clearance
在一个BFC中,垂直方向上相邻的块级盒子产生外边距塌陷,本文要说一个特殊的外边距塌陷情况,即当垂直方向上,两个块级盒子之间有个浮动元素相隔时,这个时候会产生什么样的效果呢?
.outer{
overflow: auto;
width: 300px;
height: 500px;
border: 2px solid #6666FF;
}
.box{
width: 100px;
height: 100px;
font-family: "simhei";
}
.top{
margin-bottom: 20px;
background: #CC6600;
}
.float{
/*float: left;*/浮动部分被注释掉了
}
.bottom{
margin-top: 10px;
background: #33FF66;
}
<div class="outer">
<div class="top box">top</div>
<div class="float"></div>
<div class="bottom box">bottom</div>
</div>
效果图:

然后我把中间的div设置一下:
.float{
float: left;
margin-bottom: 10px;
background: #9900CC;
width: 50px;
height: 50px;
}
<div class="float">float</div>
效果如图:

可知:浮动元素不会影响后续块级盒子与前面块级盒子的外边距塌陷。
但当我们利用bottom清除浮动时
.bottom{
margin-top: 10px;
background: #33FF66;
clear: both;
}
效果图:
可知:使用清除浮动属性的元素,它的外边距塌陷规则变成如下规则:闭合浮动的盒子的border-top始终和浮动元素的margin-bottom底部重合。而在闭合浮动的盒子的margin-top上方,直到top盒子的margin-bottom底部这段距离,就是我们所说的clearance。
验证:
- 给浮动元素加上margin-top
.float{
float: left;
margin-top: 10px;
margin-bottom: 10px;
background: #9900CC;
width: 50px;
height: 50px;
}

2.调整浮动元素的高度和margin
.float{
float: left;
margin-top: 5px;
margin-bottom: 5px;
background: #9900CC;
width: 50px;
height: 5px;
}
.bottom{
margin-top: 20px;
background: #33FF66;
clear: both;
}
效果图:
此时bottom元素的margin-top和top元素的margin-bottom重合了5px。此时clearance的值是-5px。
通过上面两个验证,我们就可以知道有浮动元素时,闭合浮动元素的clearance是怎么计算的了。一个基本原则就是闭合浮动的元素的border-top与浮动元素的margin-bottom重合。
对浮动元素的理解
另外,从上面的验证2中我们也可以总结出,浮动元素与border,padding这样的屏蔽外边距塌陷的属性不同,浮动元素是脱离文档流的,所以当浮动元素没有大到足以分开BFC中的相邻盒子时,相邻盒子的垂直margin还是会重叠的。
参考资料:
http://www.w3cplus.com/css/understanding-bfc-and-margin-collapse.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构