CSS中清除浮动的方式

来源:互联网 发布:蒙古作文软件 编辑:程序博客网 时间:2024/06/03 23:00

什么是浮动?

使元素脱离文档流(标准流),按照指定方式发生移动,遇到父级边界或者相邻的浮动元素就停下来的一种现象。

float:left|right|inherit|initial|none;

下面看一个例子:

<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title>浮动</title><style type="text/css"> #box{width:400px;border:1px solid blue;}.float{width:100px;height:100px;    float:left;}#box1{background-color:red;}#box2{background-color:green;  }#box3{background-color:yellow;}</style></head><body><div id="box"><div id="box1" class="float">div1</div><div id="box2" class="float">div2</div><div id="box3" class="float">div3</div></div></body></html>

效果图:

从上面现象,div1、div2、div3因设置了float:left;向左浮动了,但是最外层的div却没有被撑开,显示成了一条线,也就是最外层的div高度塌陷了。那什么情况一般会出现高度塌陷呢?

一般使父元素没有设置高度,而子元素都设置了浮动,此时父元素就会发生高度塌陷。

那么怎样去解决高度塌陷的问题呢?下面就总结几种清除浮动的方法。

1、给父级设置适当的高度

#box{width:400px;height:100px;border:1px solid blue;}

效果图:

此方法只适合高度固定的布局。

2、结尾处加空div标签clear:both

html:

<div id="box"><div id="box1" class="float">div1</div><div id="box2" class="float">div2</div><div id="box3" class="float">div3</div><div class="clear"></div></div>

css:

#box {width:400px;border:1px solid blue;}.float {width:100px;height:100px;float:left;}#box1 {background-color:red;}#box2 {background-color:green;}#box3 {background-color:yellow;}.clear {clear:both;}

clear:left | right | both | none | inherit:元素的某个方向上不能有浮动元素 
clear:both:在左右两侧均不允许浮动元素。

3、父级div定义overflow:hidden

#box {width:400px;border:1px solid blue;overflow:hidden;zoom:1; //兼容IE6 IE7}

4、使用after伪类清除浮动(主流,推荐使用)

html:

<div id="box" class="clearfix"><div id="box1" class="float">div1</div><div id="box2" class="float">div2</div><div id="box3" class="float">div3</div></div>

css:

.clearfix:after {content:".";clear:both;display:block;height:0;overflow:hidden;visibility:hidden;;}.clearfix {*zoom:1; /* IE/7/6*/}

此种方法的写法很固定,一般可以写在一个公共的地方。

.clear:after{content:'';display:block;clear:both;height:0;overflow:hidden;visibility:hidden;}.clear{zoom:1;}

对于不同清除浮动的方式,一般具体问题具体解决,以上只是介绍了几种主流以及兼容性比较好的方式。

好文推荐:http://www.cnblogs.com/zhongweizhu/p/6003537.html
http://www.cnblogs.com/AnotherLife/p/5800751.html