外边距塌陷之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>

效果图:

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

效果如图:

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

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;
	}
效果图:
Paste_Image.png
此时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

posted on   wudipmd  阅读(331)  评论(0编辑  收藏  举报

编辑推荐:
· 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语句:使用策略模式优化代码结构

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示