页面布局中常用的清除浮动的方法
因为在布局中碰到这个问题所以在网上查找了一些资料,布局时基本上都避免不了使用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; } |
方法二:父容器设置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类就可以了。
这些方法,经过验证确实解决了float浮动问题,但是我自己还是比较喜欢使用clear:both;这个方法。
还没有评论,来说两句吧...