前言
在沒有出現(xiàn)flex布局之前,幾乎所有的左右布局都是使用float進行浮動的。flex布局兼容性不太好,一些老的瀏覽器沒有使用這個css3的新特性,所以如果考慮到兼容問題,就可以考慮使用float進行布局了。但是使用了float屬性的元素會脫離標準的文檔流,顧名思義,float(浮動)就說明了它的用意,即浮動在其他元素上。所以對于父元素來說,加了float的子元素是漂浮在上面的,而下層的元素則會擠上來,這樣非常不符合視覺要求。

浮動的盒子
圖中紅色邊框的元素是加了邊框的元素,而我是其他的內(nèi)容的元素則是和浮動元素父元素的同級別的元素,可以看到,這樣是很不美觀的,按照道理,我是其他的內(nèi)容的元素應該顯示在邊框元素的下方。所以清除浮動就顯得很有必要了
解決
方法一:給父元素添加合適的高度
css
.des_wrap {
background-color: orange;
}
.container {
height: 120px;
}
.box {
float: left;
width: 100px;
height: 100px;
border: 1px solid red;
}
html
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="des_wrap">
<h3>清除浮動 - 給父元素設置高度</h3>
<p>給父元素設置指定的高度</p>
</div>
說明:container是浮動元素的父元素,給父元素添加了120px的高度。效果如下:

方法二:隔墻法
給最后一個浮動盒子處添加一個元素,加上clear:both;屬性
css
.des_wrap {
background-color: orange;
}
.container {
height: 120px;
}
.box {
float: left;
width: 100px;
height: 100px;
border: 1px solid red;
}
.clear {
clear: both;
}
html
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="clear"></div>
</div>
<div class="des_wrap">
<h3>清除浮動 - 隔墻法</h3>
<p>給最后一個浮動盒子處添加一個元素,加上clear:both;屬性</p>
</div>
效果

方法三:給父元素添加overflow
給浮動元素的父元素的樣式overflow除了visible值以外的值
css
.des_wrap {
background-color: orange;
}
.container {
overflow: hidden;
/* overflow: visible; */
}
.box {
float: left;
width: 100px;
height: 100px;
border: 1px solid red;
}
html
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="des_wrap">
<h3>清除浮動 - overflow</h3>
<p>給浮動元素的父元素的樣式overflow除了visible值以外的值</p>
</div>
效果

方法四:利用父元素的偽元素
給浮動元素的父元素的偽元素添加clear:both;屬性
css
.des_wrap {
background-color: orange;
}
.container {
}
.box {
float: left;
width: 100px;
height: 100px;
border: 1px solid red;
}
.clearfix::after {
content: '';
display: block;
height: 0;
visibility: hidden;
clear: both;
}
html
<div class="container clearfix">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="des_wrap">
<h3>清除浮動 - 偽元素</h3>
<p>給浮動元素的父元素的偽元素添加clear:both;屬性</p>
</div>
效果圖

方法五:雙偽元素
css
.des_wrap {
background-color: orange;
}
.container {
}
.box {
float: left;
width: 100px;
height: 100px;
border: 1px solid red;
}
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
.clearfix::after {
clear: both;
}
html
<div class="container clearfix">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="des_wrap">
<h3>清除浮動 - 雙偽元素</h3>
<p>給浮動元素的父元素的偽元素添加clear:both;屬性</p>
</div>
總結
日常生活中,使用比較頻繁的是方法三和方法四