clear float
1.爲父元素添加overflow:hidden
第一個方法很簡單,缺點是不太直觀,即爲父元素應用overflow:hidden,以強制它包圍浮動元素。
eg.
<section>
<img src = "images/rubber_duck2.jpg" />
<p>It's fun to float.</p>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>
section{border:1px solid blue; margin:0 0 10px 0; overflow:hidden;}
img{float:left;}
p{border:1px solid red;}
overflow:hidden;它能可靠的迫使父元素包含其浮動的子元素
2.同時浮動父元素
section{border:1px solid blue; float:left; width:100%;}
img{float:left;}
footer{border:1px solid red; clear:left;}
浮動section以後,不管其子元素是否浮動,它都會緊緊的包圍住它的子元素。因此需要用width:100%再讓section與瀏覽器容器同寬。另外,由於section現在也浮動了,所以footer會努力往上擠到它旁邊去。爲了強制footer依然待在section下方,要給它應用clear:left。被清除的元素不會被提升到浮動元素的旁邊。
3.添加非浮動的清除元素
<section>
<img src = "images/rubber_duck2.jpg" />
<p>It's fun to float.</p>
<div class = "clear_me"></div>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>
section{border:1px solid blue; float:left; width:100%;}
img{float:left;}
.clear_me{clear:left;}
footer{border:1px solid red; clear:left;}
這樣,浮動的元素被父元素包圍住了。
如果你特別不想添加這個純表現性元素,我再告訴你一個用css來添加這個清除元素的方法。首先,要給section添加一個類。
<section class="clearfix">
<img src = "images/rubber_duck2.jpg" />
<p>It's fun to float.</p>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>
然後,再使用這個神奇的clearfix的規則!
.clearfix:after{
content:".";
display:block;
height:0;
visibility:hidden;
clear:both;
}
這個clearfix規則也叫僞元素清除法,它最早是由程序員Tony Aslett發明的,它只添加了一個清除的包含句點作爲非浮動元素(必須有內容,而句點是最小的內容)。規則中的其他聲明是爲了確保這個僞元素沒有高度,而且在頁面上不可見。
此外,沒有父元素時如何清除浮動
<section class="clearfix">
<img src = "images/rubber_duck2.jpg" />
<p class="clearfix">It's fun to float.</p>
<img src = "images/rubber_duck2.jpg" />
<p class="clearfix">It's fun to float.</p>
<img src = "images/rubber_duck2.jpg" />
<p class="clearfix">It's fun to float.</p>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>
給每一個段落都加上clearfix類,這樣無論將來哪個段落的文本高度低於圖片了,頁面佈局都不會被破壞
希望我的入坑經驗對你有所幫助,願聖光與你同在