清除浮动主要是为了解决,父元素因为子级元素浮动引起的内部高度为0(高度塌陷)的问题 如下所示:
<div class="father"> <div class="son" style=" width: 300px; background: pink;">111</div> <div class="son" style="width: 200px; background: wheat;">222</div> </div> <div class="box">333</div>css样式如下:
<style> .father { border: 1px solid black; } .son { height: 200px; } .box { width: 200px; background: yellowgreen; } </style>当父元素未设置高度,且子元素未设置浮动时,父元素被子元素撑开
当父元素未设置高度,且子元素设置浮动时,父元素产生高度塌陷 css样式如下:
<style> .father { border: 1px solid black; } .son { height: 200px; /* float: left; */ } .box { width: 200px; background: yellowgreen; } </style>效果如下:
额外标签法(在最后一个浮动标签后,新加一个标签,给其设置clear:both;)(不推荐)
<div class="father"> <div class="son" style="background: pink;">111</div> <div class="son" style="background: wheat;">222</div> <div style="clear: both;"></div> </div> <div class="box">333</div>效果如下: 缺点:添加无意义标签,语义化差
通过触发BFC方式,实现清除浮动(父元素设置overflow:hidden)(不推荐)
<style> .father { width: 600px; border: 1px solid black; overflow: hidden; } </style>缺点:内容增多的时候容易造成不会自动换行导致内容被隐藏掉,无法显示要溢出的元素 HTML代码如下:
<div class="father"> <div class="son" style="width: 300px; background: pink;">111</div> <div class="son" style="width: 200px; background: wheat;">222</div> 44444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444 </div> <div class="box">333</div>当未给父元素设置overflow:hidden,效果如下: 当设置overflow:hidden,效果如下:
使用after伪元素清除浮动(推荐使用)
.clearfix:after,.clearfix:before{ content: ""; display: table; } .clearfix:after{ clear: both; } .clearfix{ *zoom: 1; } <div class="father clearfix"> <div class="son" style=" width: 300px; background: pink;">111</div> <div class="son" style="width: 200px; background: wheat;">222</div> </div> <div class="box">333</div>使用before和after双伪元素清除浮动
.clearfix:after,.clearfix:before{ content: ""; display: table; } .clearfix:after{ clear: both; } .clearfix{ *zoom: 1; } <div class="father clearfix"> <div class="son" style=" width: 300px; background: pink;">111</div> <div class="son" style="width: 200px; background: wheat;">222</div> </div> <div class="box">333</div>