首先,为什么要使用 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; } |
 |