首先,為什么要使用 clearfix(清除浮動)?
以下學習整理來源:https://www.jianshu.com/p/9d6a6fc3e398
通常我們在寫html+css的時候,如果一個父級元素內部的子元素是浮動的(float),那么常會發生父元素不能被子元素正常撐開的情況,如下圖所示:
HTML代碼 |
CSS代碼 |
效果 |
<body> <div class="content"> <div class="first"> 第一個 </div> <div class="second"> 第二個 </div> <div class="third"> 第三個 </div> </div> </body> |
.content{ border: 1px solid; background: black; } .first{ width: 100px; height: 100px; float: left; background: lightblue; } .second{ width: 200px; height: 200px; background: lightcoral; float: left; } .third{ width: 150px; background: lightgray; height: 150px; float: left; } |
 |
可以看到,content這個父元素完全沒有被子元素撐開(我定義content元素背景為黑色,有邊框,現在只顯示了一條線);
再舉一個例子:
HTML代碼 |
CSS代碼 |
效果 |
<body> <div class="container"> <div class="left">left</div> <div class="right">right</div> </div> <div class="footer">footer</div> </body> |
.container { width: 500px; background-color: black; border: 1px solid; } .left { width: 200px; height: 300px; background-color: lightcoral; float: left; } .right { width: 200px; height: 200px; background-color: lightblue; float: right; } .footer { width: 400px; height: 50px; background-color: lightgray; } |
 |
我們可以看到,雖然footer在container外部,卻沒位於底端,因為container內部子元素為float,導致container並沒有被撐開;
如果我們給footer添加 clear:both;,布局問題可以被解決,但是container依舊沒有被撐開,有一種強行解決問題的感覺。
要解決此問題,我們可以給container添加一個類,叫做clearfix,下面是clearfix的實現形式(之一):
HTML代碼 |
CSS代碼 |
效果 |
<body> <div class="container clearfix"> <div class="left">left</div> <div class="right">right</div> </div> <div class="footer">footer</div> </body> |
.container { width: 500px; background-color: black; border: 1px solid; } .left { width: 200px; height: 300px; background-color: lightcoral; float: left; } .right { width: 200px; height: 200px; background-color: lightblue; float: right; } .footer { width: 400px; height: 50px; background-color: lightgray; } .clearfix:after { visibility: hidden; display: block; font-size: 0; content: " "; clear: both; height: 0; } |
 |