清除浮動是CSS中常見的問題,下面就來總結下平時遇到的浮動問題。
<div style="background:yellow;border:1px solid red;width:320px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
由上圖可以看出,我們內部DIV都採取了浮動的方式實現了左右佈局,然而,外部div,由於內部浮動的緣故沒有展示出應有的結構,相應的如果後面還有其他元素的話,就會出現重疊的問題。所以這種情況下,我們需要使用清除浮動,來使外部DIV佔有需要的空間。清除浮動的方式有很多種:
1 因爲浮動後父級元素沒有被內部元素撐起來,那麼我們可以直接給父級元素一個合適的高度,這樣就可以清除浮動了。
<div style="background:yellow;border:1px solid red;width:320px;/*清除浮動代碼*/height:120px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
添加高度以後,即使裏面浮動,父級元素還是會佔用相應的高度。這樣就有一個缺點:如果高度不能確定時,我們就不能給父級元素添加合理的高度了。
2 在浮動的元素後添加沒有浮動的空標籤
<div style="background:yellow;border:1px solid red;width:320px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
<div style="clear:both;"></div>
</div>
添加沒有浮動的元素,且clear:both,同樣也可以解決浮動的問題,但是問題來了,這樣的話,如果含有浮動的元素過多,每一個都向後面添加一個空元素的話,勢必早上結構冗餘,降低性能。
3 給父級元素定義僞類:after和zoom
<style>
.father:after{
content:'';
clear:both;
height:0;
display:block;
visibility: hidden;
}
.father:after{
zoom:1;
}
</style>
<div class="father" style="background:yellow;border:1px solid red;width:320px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
在這裏:after僞類的作用相當於給浮動元素後天添加一個空元素,但是只需要幾行CSS代碼,比較節省空間,zoom的作用是用來兼容瀏覽器的。
4 給父元素定義overflow:hidden/auto;
當使用overflow時,父元素必須要定義width.
<div style="background:yellow;border:1px solid red;/*清除浮動代碼*/width:320px;overflow:auto;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
<div style="background:yellow;border:1px solid red;/*清除浮動代碼*/width:320px;overflow:hidden;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
使用overflow也會出現相應的問題,overflow:auto時,如果超出父級寬度就會出現滾動條,overflow:hidden時如果超出父級元素寬度會被隱藏。所以要掌握好父級元素的寬度才行。