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

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

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

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

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

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


当前回答

我最喜欢的方法是在css / scss文档中创建一个clearfix类,如下所示

.clearfix{
    clear:both;
}

然后在我的html文档中调用它,如下所示

<html>
  <div class="div-number-one">
    Some Content before the clearfix
  </div>

  <!-- Let's say we need to clearfix Here between these two divs --->
  <div class="clearfix"></div>

  <div class="div-number-two">
    Some more content after the clearfix
  </div>
</html>

其他回答

我已经尝试了所有这些解决方案,当我使用下面的代码时,会自动添加一个大的边距到<html>元素:

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

最后,我通过添加font-size: 0来解决边缘问题;到上面的CSS。

我建议使用下面的,这是从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:两者;到页脚。这并不需要额外的div或类。

我也浮动#content,这样两列都包含浮动。也因为它将允许您清除#content内的元素而不清除侧栏。

包装器也是如此,您需要将其设置为块格式化上下文来包装这两列。

这篇文章提到了一些你可以使用的触发器: 块格式化上下文。

这是一个相当简洁的解决方案:

/* For modern browsers */
.cf:before,
.cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

/* For IE 6/7 (trigger hasLayout) */
.cf {
    zoom:1;
}

它可以在Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+中运行 包括:before选择器是不需要清除浮点数的, 但它可以防止现代浏览器的页边距崩溃。这 确保在缩放:1时与IE 6/7的视觉一致性 应用。

从http://nicolasgallagher.com/micro-clearfix-hack/