清除float浮动三种方式
2016-05-08 17:39
239 查看
Float的作用?
w3c的官方解释:Content flows down the right side of a left-floated box and down the left side of a right-floated box … Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn’t exist.
看一个例子:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <style> .parent { background: blue; height: 400px; color: white; font-family: Arial, sans-serif; } .child1 { width: 30px; height: 30px; background: red; float: left; } .child2 { background: green; height: 100px; } </style> </head> <body> <div class="parent"> <div class="child1"></div> <div class="child2">This text flows around the red box. The green box that holds the text doesn't.</div> </div> </body> </html>
View Code
效果如下:
注意到绿色的box表现的就像红色的box根本不存在一样,但是白色的文字却“浮动”在红色box周围。
这就是float做的事情:它们导致其他的浮动元素和inline内容浮动在它们周围,但是其他block box却完全不理会float。
w3c的定义就像是在描述绝对定位元素一样,我更加倾向于将float描述成float是脱离正常流(normal flow)且和兄弟block元素相关的。
不管怎样解释,你应该知道不论浏览器怎样先进,它们永远不会自动的清除浮动——因为float的行为不是一个bug,而是特点。
清除浮动的方法
让我们先说主流的方法:clear: both/left/right
除了“none”以外的任何属性值都将导致元素相应位置不允许浮动。
overflow: hidden/auto
float导致了元素坍塌,如果你想让父元素包含所有的float属性元素,那么考虑在父元素上使用overlow:hidden/auto
clearfix
最好的方法是使用clearfix属性,下面的代码适用到IE6。
.clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } /* For IE 6/7 only */ .clearfix { *zoom: 1; }
如果你想适应IE8及其以上的,只要
.clearfix:after { content: ""; display: table; clear: both; }
你所要做的就是将clearfix类添加到包含floated的父元素上,你当然也可以使用overlow:hidden但是会导致很多布局上的其他问题。
相关文章推荐
- Android之十一Toast 自定义Toast的实现方法,及其说明
- POJ 3694 Network 双联通分量 + lca
- struts2中页面访问action的url问题,或许很简单
- excel截取单元格中部分内容
- ScrollView+ListView解决办法
- Android 干货App开发总结
- 关于EnumerateObjectsUsingBlock和for-in之间的较量
- php strtotime 和 date 日期操作
- C/C++自定义方式实现字符串的大小写转换
- php面向对象编程self和static的区别
- 把一个List集合有规律的插入另一个List集合中
- 20145326 《Java程序设计》实验五——Java网络编程及安全实验报告
- Bootstrap学习笔记
- 网站性能优化
- Filter
- java:排序算法
- 网络赚钱靠谱项目推荐和骗局陷阱
- (水)POJ-1862 哈夫曼树变形
- Xcode-Xcode 7.3 解决不能自动联想问题-备
- 设计模式之解释器模式