清除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可是會致使不少佈局上的其餘問題。

相關文章
相關標籤/搜索