css - 将 div 高度设置为自动时不显示背景颜色!为什么?

标签 css html height

当我将其高度设置为自动时,#container 的背景色不显示。但是当我将它设置为固定高度(如 1000 像素)时它确实会显示。我试过“溢出:自动”,但没有用。我该如何解决?我确实希望 #container 根据其内容垂直扩展,我也想显示其背景颜色。任何想法将不胜感激!

这是 HTML:

<div id="container">
    <div id="main">
        <div id="div1">text text text text text text text text text text text texttexttext text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text</div>
        <div id="div2">text text text text text text text text text text text texttexttext</div>
        <div class="clear"></div>
    </div><!--end of main-->
</div><!--end of container-->

这是 CSS:

#container {
    background-color: rgb(255, 102, 204);
    height: auto;
    width: 1200px;
    position: absolute;
}
#container #main {
    background-color: rgb(204, 51, 0);
    height: auto;
    width: 900px;
    position: absolute;
    overflow: auto;
}
#container #main #div1 {
    background-color: rgb(0, 204, 255);
    float: left;
    width: 300px;
    padding: 5px;
    height: auto;
    margin: 20px;
}
#container #main #div2 {
    background-color: rgb(0, 153, 153);
    height: auto;
    width: 400px;
    float: left;
    margin: 10px;
}
.clear {
    clear: both;
}

最佳答案

您遇到的问题是 #main divposition:absolute;。您必须考虑带有 position:absolute;position:fixed; 的元素已从正常流中移除,因此它们基本上不在其父元素中。

here is your code running

有关更多详细信息,您可以查看 w3schools

希望对你有帮助

关于css - 将 div 高度设置为自动时不显示背景颜色!为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18967950/

相关文章:

CSS 高度 = 宽度?

CSS:如何计算 block 元素的高度?

html - 为什么 BG 颜色不显示?

html - 为什么类 ="btn btn-default"而不是只有类 ="btn-default"

html - 如何使用 css 更改 html 表格中每个单词实例的颜色?

javascript - 灯箱上带有 slider 的图库

html - Firefox CSSCoverage 工具 - 保存使用的 CSS

html - 如何突破位置 :sticky in a list of items?

ios - iPad 的 flex - 高度

javascript - 将输入按钮的文本拆分为两行,在另一行之上