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

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

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

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

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

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


当前回答

我建议使用下面的,这是从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;  
}

其他回答

一个新的显示值似乎是在一行中的作业。

display: flow-root;

来自W3规范:“元素生成一个块容器盒,并使用流布局布局其内容。它总是为其内容建立一个新的块格式上下文。”

信息: https://www.w3.org/TR/css-display-3/#valdef-display-flow-root https://www.chromestatus.com/feature/5769454877147136

※如图所示、在上面的链接中,支持目前有限的后备支持像使用以下可能: https://github.com/fliptheweb/postcss-flow-root

假设你正在使用这个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中也是如此。

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

我在官方的CLEARFIX-Method中发现了一个bug: 交通部没有字体大小的规定。 如果你设置height = 0并且DOM-Tree中的第一个元素具有类clearfix,那么页面底部总会有12px的边距:)

你必须像这样修正它:

/* float clearing for everyone else */
.clearfix:after{
  clear: both;
  content: ".";
  display: block;
  height: 0;
  visibility: hidden;
  font-size: 0;
}

它现在是yaml布局的一部分…看看吧,非常有趣! http://www.yaml.de/en/home.html

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

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