30

我的 mainContainer 高度不跟随他们的孩子宽度

这是我的代码你有什么建议请指教。

我需要 CSS 解决方案而不是 JavaScript,所以在此先感谢

<div id="mainContainer">
    <div id="leftContent">

    </div>

    <div id="rightContent">

    </div>
</div>

这是我的CSS

#mainContainer{
    width: 1000px;
    /*height: 1000px;*/
    height:auto;
    margin-left:auto;
    margin-right:auto;
    background-color: #ff6600;
    padding-bottom: 20px;
}
#leftContent{
    height: 100px;
    float: left;
    width: 380px;
    background-color: violet;
}
#rightContent{
    height: 100px;
    float: right;
    width: 620px;
    background-color: yellow;
}
4

3 回答 3

81

添加overflow:hidden;到容器中:

#mainContainer{
    width: 1000px;
    /*height: 1000px;*/
    height:auto;
    margin-left:auto;
    margin-right:auto;
    background-color: #ff6600;
    padding-bottom: 20px;

    overflow: hidden; /* <--- here */
}

因为它的内容是浮动的,所以容器 div 会塌陷。使用“clearfix”类,或者正如我提到的,添加overflow:hidden将导致容器包含浮动元素。

更新解释为什么这个工作可以在这里找到:https ://stackoverflow.com/a/9193270/1588648

... 和这里:

为了让他们(浏览器)计算溢出块边界的内容(因此应该被隐藏),他们需要知道块的大小。因为这些块没有明确的高度设置,浏览器使用计算的内容高度来代替。

http://www.stubbornella.org/content/2009/07/23/overflow-a-secret-benefit/

于 2013-05-11T03:32:44.957 回答
12

您需要清除浮动元素,overflow: hidden;用于#mainContainer

演示

替代:(您可以添加clear: both;到清除浮动)

演示

或者您也可以自行清除浮动元素(仅当您希望支持 IE9=+

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

为什么会发生这种情况?

于 2013-05-11T03:33:31.033 回答
4

使用溢出:隐藏和清除浮动

#mainContainer{
    width: 1000px;
    height:auto;
    margin-left:auto;
    margin-right:auto;
    background-color: #ff6600;
    padding-bottom: 20px;

    overflow: hidden;
    clear: both;
}
于 2013-05-11T03:37:47.567 回答