我有一个古老的问题,一个div包装两列布局。我的侧边栏是浮动的,所以我的容器div不能包装内容和侧边栏。

<div id="container">
  <div id="content"></div>
  <div id="sidebar"></div>
</div>

似乎有很多方法可以修复Firefox中的明显错误:

< br清楚= "所有" / > 溢出:汽车 隐藏溢出:

在我的情况下,唯一一个似乎正确工作的是<br clear="all"/>解决方案,这有点邋遢。溢出:auto给我讨厌的滚动条,溢出:隐藏肯定有副作用。 此外,IE7显然不应该因为它的错误行为而遭受这个问题,但在我的情况下,它遭受的问题和Firefox一样。

目前可用的哪种方法是最稳健的?


当前回答

你也可以把这个放在你的CSS中:

.cb:after{
  visibility: hidden;
  display: block;
  content: ".";
  clear: both;
  height: 0;
}

*:first-child+html .cb{zoom: 1} /* for IE7 */

并添加类“cb”到你的父div:

<div id="container" class="cb">

您不需要在原始代码中添加任何其他内容。

其他回答

使用LESS (http://lesscss.org/),你可以创建一个方便的clearfix helper:

.clearfix() {
  zoom: 1;
  &:before { 
    content: ''; 
    display: block; 
  }
  &:after { 
    content: ''; 
    display: table; 
    clear: both; 
  }
}

然后将其用于有问题的容器,例如:

<!-- HTML -->
<div id="container">
  <div id="content"></div>
  <div id="sidebar"></div>
</div>
/* LESS */
div#container {
  .clearfix();
}

如果浮动容器有父元素,在ie6中使用overflow:hidden/auto和height就足够了。

#测试中的任何一个都可以工作,下面所述的HTML可以清除浮动。

#test {
  overflow:hidden; // or auto;
  _height:1%; forces hasLayout in IE6
}

<div id="test">
  <div style="floatLeft"></div>
  <div style="random"></div>
</div>

如果这在ie6中不能正常工作,只需要浮动父节点来清除浮动。

#test {
  float: left; // using float to clear float
  width: 99%;
}

从来没有真正需要任何其他类型的清理。也许是我编写HTML的方式。

我总是使用micro-clearfix:

.cf:before,
.cf:after {
    content: " ";
    display: table;
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 */
.cf {
    *zoom: 1;
}

在Cascade框架中,我甚至在块级元素上默认应用它。在我看来,默认情况下将它应用于块级元素,使块级元素的行为比传统行为更直观。它还使我更容易向Cascade Framework(它支持IE6-8和现代浏览器)添加对旧浏览器的支持。

我建议使用下面的,这是从http://html5boilerplate.com/

/* >> The Magnificent CLEARFIX << */
.clearfix:after { 
  content: "."; 
  display: block; 
  height: 0; 
  clear: both; 
  visibility: hidden; 
}
.clearfix { 
  display: inline-block;  
}
* html .clearfix {  
  height: 1%;  
} /* Hides from IE-mac \*/
.clearfix {  
  display: block;  
}

我只用:-

.clear:after{
  clear: both;
  content: "";
  display: block;
}

工作最好,兼容IE8+:)