方法一:添加新的元素 、应用 clear:both;
<div class="outer">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="clear"></div>
</div>
.clear{clear:both; height: 0; line-height: 0; font-size: 0}
方法二:父级div定义 overflow: auto
<div class="outer over-flow"> //这里添加了一个class
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<!--<div class="clear"></div>-->
</div>
.over-flow{
overflow: auto; zoom: 1; //zoom: 1; 是在处理兼容性问题
}
3、使用after伪对象清除浮动。 该方法只适用于非IE浏览器 。具体写法可参照以下示例。使用中需注意以下几点。
一、该方法中必须为需要清除浮动元素的伪对象中设置height:0,否则该元素会比实际高出若干像素;
二、content属性是必须的,但其值可以为空,content属性的值设为”.”,但我发现为空亦是可以的;
#layout{background:#FF9;}
#layout:after{display:block;clear:both;content:”";visibility:hidden;height:0;}
#left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
#right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
<div id=”left”>Left</div>
<div id=”right”>Right</div>
</div>
如果不清除浮动,那么为父元素设置的background-color和margin以及padding都不能正确显示