CSS 父母身高不跟随他们的浮动孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16493456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parent Height doesn't follow their float children
提问by Jongz Puangput
My mainContainer height doesn't follow their children width
我的 mainContainer 高度跟不上他们孩子的宽度
and here is my code do you have any suggestion please advise.
这是我的代码你有什么建议请指教。
I need the CSS solution not JavaScript so thank in advance
我需要 CSS 解决方案而不是 JavaScript 所以提前致谢
<div id="mainContainer">
<div id="leftContent">
</div>
<div id="rightContent">
</div>
</div>
and here is my css
这是我的 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;
}
回答by Kevin Boucher
Add overflow:hidden;
to the container:
添加overflow:hidden;
到容器中:
#mainContainer{
width: 1000px;
/*height: 1000px;*/
height:auto;
margin-left:auto;
margin-right:auto;
background-color: #ff6600;
padding-bottom: 20px;
overflow: hidden; /* <--- here */
}
Because its content is floated, the container div collapses. Using a 'clearfix' class or, as I mentioned, adding overflow:hidden
will cause the container to contain the floated elements.
因为它的内容是浮动的,所以容器 div 会折叠起来。使用“clearfix”类,或者,正如我提到的,添加overflow:hidden
将导致容器包含浮动元素。
UPDATEExplanation of why this works can be found here: https://stackoverflow.com/a/9193270/1588648
可以在这里找到更新原因的解释:https: //stackoverflow.com/a/9193270/1588648
... and here:
... 和这里:
In order for them (browsers) to calculate what overflowed the bounds of the block (and thus should be hidden), they needed to know the size of the block. Because these blocks do no have an explicit height set, the browsers used the calculated height of the content instead.
为了让他们(浏览器)计算溢出块边界的内容(因此应该隐藏),他们需要知道块的大小。因为这些块没有明确的高度设置,浏览器使用计算的内容高度代替。
http://www.stubbornella.org/content/2009/07/23/overflow-a-secret-benefit/
http://www.stubbornella.org/content/2009/07/23/overflow-a-secret-benefit/
回答by Mr. Alien
You need to clear your floating elements, use overflow: hidden;
for #mainContainer
您需要清除浮动元素,overflow: hidden;
用于#mainContainer
Alternate : (You can add clear: both;
to clear floats)
替代:(您可以添加clear: both;
清除浮动)
Or you can also self clear floating elements (Only if you wish to support IE9=+
或者您也可以自行清除浮动元素(仅当您希望支持 IE9=+
.clear:after {
content: "";
clear: both;
display: table;
}
回答by Tamil Selvan C
Use overflow: hidden and clear a float
使用溢出:隐藏并清除浮动
#mainContainer{
width: 1000px;
height:auto;
margin-left:auto;
margin-right:auto;
background-color: #ff6600;
padding-bottom: 20px;
overflow: hidden;
clear: both;
}