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

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

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

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

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

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


当前回答

.clearFix:after { 
    content: "";
    display: table;  
    clear: both;  
}

其他回答

我总是浮动网格的主要部分,并应用clear:两者;到页脚。这并不需要额外的div或类。

当我们在div元素中使用float属性时,clearfix就可以解决这个问题。如果我们使用两个div元素一个作为float:left;另一个是float:right;我们可以对两个div元素的父元素使用clearfix。如果我们拒绝使用clearfix不必要的空间填充下面的内容和网站结构将被打破。

clearfix是一种元素自动清除自身的方法, 这样您就不需要添加额外的标记。

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}
.cleaner {
  clear: both;
}

通常你需要做以下事情:

<div style="float: left;">Sidebar</div>
<div class="cleaner"></div> <!-- Clear the float -->

使用clearfix,您只需要这样做

<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->

你也可以把这个放在你的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">

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

如果浮动容器有父元素,在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的方式。