2

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!

Here is the 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-->

Here is the 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;
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
lei he
  • 259
  • 3
  • 8

3 Answers3

3

the problem you have is that #main div have position:absolute;. You have to take on account that element with position:absolute; or position:fixed; are removed from normal flow, so they basicly are not inside their parent.

here is your code running

for more details on that you can check w3schools

hope that helps

lazychino
  • 41
  • 3
  • 2
    don't link to w3schools: http://www.w3fools.com/. MDN (https://developer.mozilla.org/en-US/) is much better; for positioning: https://developer.mozilla.org/en-US/docs/Web/CSS/position – Ben Jackson Sep 23 '13 at 20:41
  • 3
    w3schools explains it well, MDN is better for reference and it have more up to date info – lazychino Sep 23 '13 at 20:46
2

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.

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

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

3066d0
  • 1,853
  • 1
  • 14
  • 18
1

simply add overflow:auto; in .css file for example:

#products_box{
    width:800px;
    height:auto;
    margin:auto;
    background-color:pink;
    overflow: auto;
    text-align:center;
    margin-left:200px;
}