
我们在页面布局时,基本上都避免不了使用float,但由此也会引发一些问题,尤其是在容器高度不固定时,此时它的高度完全是由内部的元素撑开的。如果内部元素还是浮动的,那么由于内部的元素脱离了文档流,父容器就不能被撑开了。如果父容器设置的有背景或者边框的话,此时就不能正常显示了,另外,父容器下边的其他容器或内容也会跟着向上“浮”, 占据上面的子容器应该占据的位置。那么,这时就需要清除浮动了。
这里总结的几种的方法主要就是针对类似于上面的问题的,但也不仅限于以上问题。主要有以下几种方法:
1、设置空标签
2、父容器设置display: inline-block
3、父容器设置overflow值auto或hidden
4、clearfix方法
下面就根据一个例子分别看一下吧。
例子:
Html结构是这样的:
|
1
2
3
4
5
6 |
<div
class="cont1"> <div
class="cols1">cols1</div> <div
class="cols2">cols2</div> cont1</div><div
class="cont2">cont2</div> |
cont1高度不固定,cols1和cols2浮动,cont2高度固定在cont1下面。
不清除浮动时的效果:

理想效果:

下面就分别用几种方法实现一下:
方法一:设置空标签
我们在容器cont1的最后面添加空标签clear:
|
1
2
3
4
5
6
7 |
<div
class="cont1"> <div
class="cols1">cols1</div> <div
class="cols2">cols2</div> cont1 <div
class="clear"></div> </div><div
class="cont2">cont2</div> |
然后对clear添加css:
|
1
2
3 |
.clear { clear: both;} |
Ok,这样就行了。
方法二:父容器设置display: inline-block
只需对父容器添加css属性display: inline-block; 就行了
|
1
2
3
4
5 |
.cont1
{ ... display: inline-block; ...} |
方法三:父容器设置overflow值auto或hidden
只需对父容器添加属性overflow: auto; 或者 overflow: hidden;
|
1
2
3
4
5 |
.cont1
{ ... overflow: auto; /*hidden也可以*/ ...} |
方法四:clearfix方法
此时需要写一个clearfix的类:
|
1
2
3
4
5
6
7
8
9 |
.clearfix:before,.clearfix:after { display: table; content: " ";} .clearfix:after { clear: both;} |
然后在cont1里面挂载上clearfix类就可以了。
以上就是总结的几种清除浮动的方法,欢迎大家提出更好的解决方法。