清除浮动两种思路:
1.利用clear属性清除浮动
2.使父容器形成BFC(Block Formatting Contexts块级格式化上下文)
利用clear属性清除浮动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除浮动</title> <style type="text/css"> .box{ width:600px; border:1px solid #333; } .same{ width:100px; height:100px; background-color:deeppink; float: left; margin:20px; } .clear{ /*clear:left;*/ clear:both; } .left{ } .cont{ /*clear:both;*/ } </style> </head> <body> <div class="box"> <div class="left same">左侧盒子</div> <div class="cont same">中间盒子</div> <div class="right same">右侧盒子</div> <div class="clear"></div> </div> </body> </html>
使用css插入元素
<div class="p floatfix"> <div class="aa same"></div> <div class="bb same"></div> <div class="cc same"></div> </div>
.floatfix:after{ content:'.'; display:block; height:0; visibility:hidden; clear:both; }
父元素添加一个不可见的块元素。
.floatfix:after{ content:'.'; display:table; clear:both; }IE6,IE7不支持伪类元素,需要使用BFC
使父元素形成BFC
父容器形成BFC:
float为left、right
overflow为hidden、auto、scroll
display为table-cell、table-caption、inlineblock
position为absolute、fixed
<div class="bfc box"> <div class="same">1</div> <div class="same">2</div> <div class="same">2</div> </div>
.same{ width:100px; height:100px; background-color:deeppink; float: left; margin:20px; } .bfc{ /*float:left;*/ overflow: hidden; }
一个相对靠谱的解决方案
在IE+、现代浏览器上使用伪元素
在IE6、7使用hasLayout
.floatfix{ *zoom:1; } .floatfix:after{ content:'.'; display:table; clear:both; }
参考:https://www.cnblogs.com/dolphinX/p/3508869.html