实现文字环绕效果,如下图所示:
Paste_Image.png
明白了float的设计初衷,就可以明白float特有的行为表现了。
我们都知道,使用float会产生一定的破坏性,如给子元素设置浮动会使父元素高度塌陷,其实这不是bug,而是为了实现文字环绕效果而产生的特性使然。
1.给受浮动影响的元素设置clear:both
2.使父元素形成BFC(IE8+,是高级浏览器特有的一个概念)或haslayout(IE6/IE7私有的概念)
两种方法的区别:
代码示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>clear与margin重叠</title>
</head>
<body>
1.
<div style="background-color: #f5f5f5;">
![](http://upload-images.jianshu.io/upload_images/1969310-8b6611e56974ea20.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<div style="clear:both; margin-bottom:100px;">clear:both;</div>
</div>
<div style="margin-top: 100px;">本文字离图片的距离是?</div>
<br><br><br><br>2.
<div style="background-color: #f5f5f5; overflow: hidden;">
![](http://upload-images.jianshu.io/upload_images/1969310-8b6611e56974ea20.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</div>
<div style="margin-top: 100px;">本文字离图片的距离是?</div>
</body>
</html>
显示效果:
Paste_Image.png
第一种:浮动元素的底加入div 且设置clear:both;(本例中margin-top和margin-bottom会发生重叠)
第二种:在浮动元素的父元素上加入overflow: hidden,使父元素形成BFC;(本列中 父元素会将整个元素包裹起来,从而不会出现塌陷和重叠显现)
clear的通常应用形式:
clear:both
声明的block水平元素,通常使用<div></div>
元素。方法的不足:添加了多余的裸露的
<div></div>
标签
clear:both
声明的伪元素:.clerafix:after{}
。方法的不足:对IE6/IE7无效。
权衡后的策略:
IE8以上的浏览器使用:
.clearfix:after{content:'';display:table;clear:both;}
IE6/IE7使用
.clearfix{*zoom:1;}
注意:切勿滥用
.clearfix
,它只应该应用于包含浮动子元素的父级元素上。