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

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

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

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

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

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


当前回答

overflow属性可以用来清除没有额外标记的浮点数:

.container { overflow: hidden; }

这适用于所有浏览器,除了IE6,你所需要做的就是启用hasLayout(缩放是我的首选方法):

.container { zoom: 1; }

http://www.quirksmode.org/css/clearing.html

其他回答

你试过这个吗:

<div style="clear:both;"/>

我用这个方法没有任何问题。

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

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

/* 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/

使用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();
}

假设你正在使用这个HTML结构:

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

下面是我将使用的CSS:

div#container {
    overflow: hidden;    /* makes element contain floated child elements */
}

div#content, div#sidebar {
    float: left;
    display: inline;    /* preemptively fixes IE6 dobule-margin bug */
}

我一直使用这个集合,它对我来说工作得很好,即使在IE6中也是如此。