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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:28:21  来源:igfitidea点击:

Why is the parent div height zero when it has floated children

htmlcss

提问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#wrapperis shown as being 0pxhigh. I would've expected it to expand till the end of div.contentand div.lbar... Why does this happen?

页面呈现正确。但是,当我检查元素时,div#wrapper显示为0px高。我会一直期待它扩大,直到年底div.contentdiv.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: hiddenon 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, floats aren't counted in the layout of their parents.

通常,floats 不计入其父级的布局中。

To prevent that, add overflow: hiddento 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%;
}