在一個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
可知:浮動元素不會影響后續(xù)塊級盒子與前面塊級盒子的外邊距塌陷。
但當我們利用bottom清除浮動時
.bottom{
margin-top: 10px;
background: #33FF66;
clear: both;
}
效果圖:
Paste_Image.png
可知:使用清除浮動屬性的元素甸饱,它的外邊距塌陷規(guī)則變成如下規(guī)則:閉合浮動的盒子的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;
}
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