Html 为什么在浮动子项时父 div 高度为零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5369954/
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
Why is the parent div height zero when it has floated children
提问by Quentin
I have the following in my CSS. All margins/paddings/borders are globally reset to 0.
我的 CSS 中有以下内容。所有边距/填充/边框都全局重置为 0。
#wrapper{width: 75%; min-width: 800px;}
.content{text-align: justify; float: right; width: 90%;}
.lbar{text-align: justify; float: left; width: 10%;}
Now when I write my HTML as
现在,当我将 HTML 编写为
<div id="wrapper">
<div class="content">
some text here
</div>
<div class="lbar">
some text here
</div>
</div>
the page renders correctly. However, when I inspect the elements, div#wrapper
is shown as being 0px
high. I would've expected it to expand till the end of div.content
and div.lbar
... Why does this happen?
页面呈现正确。但是,当我检查元素时,div#wrapper
显示为0px
高。我会一直期待它扩大,直到年底div.content
和div.lbar
...为什么会出现这种情况?
Again, the page renders fine. This behaviour just perplexes me.
同样,页面呈现良好。这种行为让我很困惑。
回答by Quentin
Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).
浮动的内容不会影响其容器的高度。该元素不包含不浮动的内容(因此没有什么可以阻止容器的高度为 0,就好像它是空的一样)。
Setting overflow: hidden
on the container will avoid that by establishing a new block formatting context. See methods for containing floatsfor other techniques and containing floatsfor an explanation about why CSS was designed this way.
overflow: hidden
在容器上设置将通过建立新的块格式上下文来避免这种情况。见包含花车方法的其他方法和含彩车有关为何CSS设计这样的解释。
回答by SLaks
Ordinarily, float
s aren't counted in the layout of their parents.
通常,float
s 不计入其父级的布局中。
To prevent that, add overflow: hidden
to the parent.
为了防止这种情况,请添加overflow: hidden
到父级。
回答by Melih
I'm not sure this is a right way but I solved it by adding display: inline-block;
to the wrapper div.
我不确定这是一个正确的方法,但我通过添加display: inline-block;
到包装器 div 来解决它。
#wrapper{
display: inline-block;
/*border: 1px black solid;*/
width: 75%;
min-width: 800px;
}
.content{
text-align: justify;
float: right;
width: 90%;
}
.lbar{
text-align: justify;
float: left;
width: 10%;
}