Html 为什么 height:auto 不适用于 2 个浮动元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19462737/
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 14:36:50  来源:igfitidea点击:

Why is height:auto not working on 2 floating elements?

htmlcss

提问by Sreeja Das

The div#inner1and div#inner2are inside the div#outer, but still the height of div#outershows as 0px with height:auto.

div#inner1div#inner2是内部的div#outer,但仍然高度div#outer显示为0像素带height:auto

How do I get the height of the child elements for the outer div?

如何获取外部 div 的子元素的高度?

This is my code:

这是我的代码:

#outer {
  width: 300px;
  height: auto;
  background: #ccc;
}

#inner1 {
  float: left;
  width: 100px;
  height: 100px;
  background: #f00;
}

#inner2 {
  float: left;
  width: 100px;
  height: 100px;
  background: #0f0;
}
<div id="outer">
  <div id="inner1"></div>
  <div id="inner2"></div>
</div>

采纳答案by Sreeja Das

Float the outer div. that will cover your all height, whatever the inner divs holding heights. But if you will provide your inner div float property. then i will suggest you to use the hack clearfix..

浮动外部div。这将覆盖您的所有高度,无论内部 div 保持高度。但是,如果您提供内部 div 浮动属性。那么我会建议你使用hack clearfix ..

    /* Assuming this HTML structure:

    <div class="clear">
        <div class="floated"></div>
        <div class="floated"></div>
        <div class="floated"></div>
    </div>
*/

.clear:before, .clear:after {
    content: "##代码##20";
    display: block;
    height: 0;
    overflow: hidden;
}

.clear:after {
    clear: both;
}

try this it will sure work

试试这个它肯定会工作

回答by Sreeja Das

Add overflow:autoto the div with id outer. This will solve your problem.

添加overflow:auto到带有 id 的 div outer。这将解决您的问题。

Demo

演示