---
title: "浮动清理另类方法"
author: "heartnn"
date: "2008-11-26T17:55:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-11-26T17:55:00Z"
id: 288209
url: "https://heartnn.iteye.com/blog/288209"
---

在进行浮动布局时，大多数人都深知，在必要的地方进行浮动清理：

> &lt;div style="clear:both;"&gt;&lt;/div&gt;

```

<div style="background:#666;">
<!-- float container -->
  <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
</div>
```

此时预览此代码，我们会发现最外层的父元素float container,并没有显示。这是因为子元素因进行了浮动，而脱离了文档流，导致父元素的height为零。  
若将代码修改为：

```

<div style="background:#666;">
  <!-- float container -->
  <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
  <div style="clear:both"></div>
</div>
```

注意，多了一段清理浮动的代码。这是一种好的CSS代码习惯，但是这种方法增加了无用的元素。这里有一种更好的方法，将HTML代码修改为：

```

<div  class="clearfix" style="background:#666;">
  <!-- float container -->
  <div style="float:left; width:30%; height:40px;background:#EEE; ">Some Content</div>
</div>
```

定义CSS类，进行“浮动清理”的控制：

```

.clearfix:after {}{
  content: ".";
  clear: both;
  height: 0;
  visibility: hidden;
  display: block;
}            /* 这是对Firefox进行的处理，因为Firefox支持生成元素，而IE所有版本都不支持生成元素 */
.clearfix {}{
  display: inline-block;     
}            /* 这是对 Mac 上的IE浏览器进行的处理 */
/**//* Hides from IE-mac \*/
* html .clearfix {}{height: 1%;}        /* 这是对 win 上的IE浏览器进行的处理 */
.clearfix {}{display: block;}        /* 这是对display: inline-block;进行的修改，重置为区块元素 */
/**//* End hide from IE-mac */
```

此时，预览以上代码( 删去这种注释 )，会发现即使子元素进行了浮动，父元素float container仍然会将其包围，进行高度自适应。

代码参考：[http://www.positioniseverything.net/easyclearing.html](http://www.positioniseverything.net/easyclearing.html)

clear元素的margin-top被重置为零，当你使用clear(left & both & right)清理一个浮动元素时，该元素的margin-top会被重置为0。所以为了创建浮动列，并使用footer进行浮动清理时，必须对浮动列（sidebar && content）都指定margin-bottom,最好margin-bottom相同。（Firefox会将margin-top重置0，而IE不重置footer的margin-top）。

例如：  
分别在Firefox和IE中运行一下代码，仔细读者会发现页脚（footer）的margin-top在火狐中并没有显示，而在IE中却出现了10像素的上边距。

```

<body>
<div id="wrapper">
    <div id="masthead">
        masthead content goes here
    </div>
    <div id="sidebar">
        sidebar content goes here
    </div>
    <div id="content">
        main content goes here
        <br/>
        main content goes here
    </div>
    <div id="footer">
        footer
    </div>
</div>

</body>
```

CSS代码

```

body {}{
    margin:0; padding:0;
    background-color:#FFFFCC;
}
#wrapper {}{
    width:800px;
    margin:0 auto;
}
/**//*Masthead*/
#masthead {}{
    padding:10px;
    background:#FFCC33;
    margin-bottom:10px;
}
/**//*Content*/
#content {}{
    float:left;
    width:60%;
    background:#CCCCCC;
}
/**//*Sidebar*/
#sidebar {}{
    float:right;
    width:36%;
    background:#999999;
}
/**//*Footer*/
#footer {}{
    clear:both;
    padding:10px;
    background:#FFCC33;
}
```