前提清除浮动都会带来一定的影响,没有那种方法是完美的
第一种:添加额外的标签
<div>
<p>添加额外标签</p>
<div style="float: left;">左</div>
<div style="float: right;">右</div>
<div style="clear: both"></div>
</div>
这个的兼容性比较好,百度在IE浏览器就是这样清除的浮动
第二种:使用br标签
形式和第一种类似
<div>
<p>添加br标签</p>
<div style="float: left;">左</div>
<div style="float: right;">右</div>
<br clear="all" />
</div>
第三种:父元素使用overflow:hidden
<div style="overflow: hidden;">
<p>父标签使用overflow:hidden</p>
<div style="float: left;">左</div>
<div style="float: right;">右</div>
</div>
第四种:父元素使用overflow:auto
<div style="overflow: auto;">
<p>父元素overflow:auto</p>
<div style="float: left;">左</div>
<div style="float: right;">右</div>
</div>
第五种:父元素使用display:table
<div style="display: table;">
<p>父元素使用display:table</p>
<div style="float: left;">左</div>
<div style="float: right;">右</div>
</div>
第六种:添加:after的伪元素(这个没怎么用过)
<style type="text/css">
.clearfix:after
{ content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {display: inline-block;} /* for IE/Mac */
</style>
<!--[if IE]>
<style type="text/css">
.clearfix {
zoom: 1;/* triggers hasLayout */
display: block;/* resets display for IE/Win */
}
</style>
[endif]鉴于 IE/Mac的市场占有率极低,我们直接忽略掉,最后精简的代码如下: -->
.clearfix:after
{
content:".";
display:block;
height:0;
visibility:hidden;
clear:both;
}
.clearfix { *zoom:1; }