将div高度设置为自动时,背景颜色不显示!为什么? [英] Background color does not show when setting a div height to auto! Why?

查看:495
本文介绍了将div高度设置为自动时,背景颜色不显示!为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#container的背景颜色在我将其高度设置为自动时不显示。但它确实显示,当我设置一个固定的高度像1000px。我试过overflow:auto,但它没有工作。我该如何解决?我想要#container根据其内容垂直展开,我想要显示其背景颜色。任何想法将非常感激!

The background-color of #container does not show when I set its height to auto. But it does show when I set it to a fixed height like 1000px. I've tried "overflow:auto", but it didn't work. How can I fix it? I do want #container to vertically expand according to its content and I want to show its background color as well. Any idea will be much appreciated!

这里是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;
}


推荐答案

绝对定位或浮动定位,不会计算父级的高度。请尝试在一些元素或容器上设置最小高度。

All of you elements are either positioned absolutely or floated, that won't compute a height for the parent. Try setting a min-height on some of your elements or atleast on the container.

给我一​​点时间,我将尝试使用解决方案设置jsfiddle: )

Give me a moment and I'll try to set up a jsfiddle with a solution :)

!看到lazychio的答案,它是你想要的。

!!! See lazychio's answer, its what you're looking for.

这篇关于将div高度设置为自动时,背景颜色不显示!为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆