外边距塌陷之clearance

在一个BFC中,垂直方向上相邻的块级盒子产生外边距塌陷,本文要说一个特殊的外边距塌陷情况,即当垂直方向上,两个块级盒子之间有个浮动元素相隔时,这个时候会产生什么样的效果呢?

.outer{
		overflow: auto;
		 300px;
		height: 500px;
		border: 2px solid #6666FF;
	}
	.box{
		 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;
		 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;
		 50px;
		height: 50px;
	}

Paste_Image.png

2.调整浮动元素的高度和margin

.float{
		float: left;
		margin-top: 5px;
		margin-bottom: 5px;
		background: #9900CC;
		 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

原文地址:https://www.cnblogs.com/woodyblog/p/6005418.html