簡單地說,浮動是由於使用了float:left或float:right或二者都有而產生的浮動,致使樣式缺失或者不正確顯示等問題;css
一、背景不能顯示
因爲浮動產生,若是對父級設置了(CSS background背景)CSS背景顏色或CSS背景圖片,而父級不能被撐開,因此致使CSS背景不能顯示。html
二、邊框不能撐開
若是父級設置了CSS邊框屬性(css border),因爲子級裏使用了float屬性,產生浮動,父級不能被撐開,致使邊框不能隨內容而被撐開。spa
三、margin padding設置值不能正確顯示
因爲浮動致使父級子級之間設置了css padding、css margin屬性的值不能正確表達。特別是上下邊的padding和margin不能正確顯示。htm
首先列舉一個小案例:圖片
<style>
.box{margin: 50px auto;border:1px solid #ccc;background: #fc9;color:#fff;}
.red{width: 80px;height: 100px;background: red;float:left;}
.sienna{width: 80px;height: 100px;background: sienna;float:left;}
.blue{width: 80px;height: 100px;background: blue;float:left;}
</style>
<body>
<div class="box">
<div class="red">1</div>
<div class="sienna">2</div>
<div class="blue">3</div>
</div>
</body>
子元素都設置了float屬性,父元素div高度不能撐開,樣式margin屬性顯示有問題;
方法一:添加新的元素 、應用 clear:both;
在浮動的盒子之下再放一個標籤,在這個標籤中使用clear:both,來清除浮動對頁面的影響.
注意:通常狀況下不會使用這一種方式來清除浮動。由於這種清除浮動的方式會增長頁面的標籤,形成結構的混亂.
.clear{clear: both;}
<div class="box">
<div class="red">1</div>
<div class="sienna">2</div>
<div class="blue">3</div>
<div class="clear"></div>
</div>
方法二:父級div定義 overflow: auto(注意:是父級div也就是這裏的 div.outer)
原理:使用overflow屬性來清除浮動有一點須要注意,overflow屬性共有三個屬性值:hidden,auto,visible。咱們可使用hiddent和auto值來清除浮動,但切記不能使用visible值。
.over-flow{ overflow: auto; zoom: 1;}/*zoom1; 是在處理兼容性問題*/
<body>
<div class="box over-flow">
<div class="red">1</div>
<div class="sienna">2</div>
<div class="blue">3</div>
</div>
</body>
方法三: 使用僞元素來清除浮動(:after,注意:做用於浮動元素的父親)
主要推薦使用這種方法清除浮動
.clearfix:after{
content:"";/*設置內容爲空*/
height:0;/*高度爲0*/
line-height:0;/*行高爲0*/
display:block;/*將文本轉爲塊級元素*/
visibility:hidden;/*將元素隱藏*/
clear:both;/*清除浮動*/
}
.clearfix{
zoom:1;/*爲了兼容IE*/
}
<body>
<div class="box clearfix">
<div class="red">1</div>
<div class="sienna">2</div>
<div class="blue">3</div>
</div>
</body>
方法四:使用雙僞元素清除浮動
.clearfix:before,.clearfix:after {
content: "";
display: block;
clear: both;
}
.clearfix {
zoom: 1;
}