清除float浮动三种方式

Float的做用?

w3c的官方解释:html

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.浏览器

看一个例子:ide

<!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周围。spa

这就是float作的事情:它们致使其余的浮动元素和inline内容浮动在它们周围,可是其余block box却彻底不理会float。code

w3c的定义就像是在描述绝对定位元素同样,我更加倾向于将float描述成float是脱离正常流(normal flow)且和兄弟block元素相关的。orm

无论怎样解释,你应该知道不论浏览器怎样先进,它们永远不会自动的清除浮动——由于float的行为不是一个bug,而是特色。htm

清除浮动的方法

让咱们先说主流的方法:blog

clear: both/left/right
除了“none”之外的任何属性值都将致使元素相应位置不容许浮动。utf-8

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可是会致使不少布局上的其余问题。

相关文章
相关标签/搜索