2013-05-11 81 views
21

我的主容器高度不遵循他们的孩子宽度父母身高不跟随他们的浮动儿童

这里是我的代码你有任何建议,请指教。

我需要提前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; 
} 
+0

你可以将一个clearfix应用于元素。家长的高度不会适应标准的浮动元素。 – 2013-05-11 03:34:01

回答

63

添加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将导致容器包含浮动元素。

UPDATE为什么这个作品说明可以在这里找到:https://stackoverflow.com/a/9193270/1588648

...这里:

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

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

+0

哇,拯救我的生命。我已经坐了3个小时没有什么值得感谢的@Kevin Boucher – 2013-05-11 03:36:53

+1

但是您能否更详细地描述为什么会溢出:隐藏解决这个问题的方法是如何让容器容纳浮动。 – 2013-05-11 03:39:28

+0

很高兴我能帮到你。快乐的编码! – 2013-05-11 03:39:58

8

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

Demo

备选:(您可以添加clear: both;清除浮动)

Demo

或者你也可以自行清晰浮动元素(只有当你想支持IE9 = +

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

Why this happens?

+2

这就是它应该做的! 'overflow:hidden'可以......好吧..只是隐藏内容。 – 2015-12-11 23:15:45

4

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

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

    overflow: hidden; 
    clear: both; 
}