您的位置:首页 > 其它

清除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但是会导致很多布局上的其他问题。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: