【问题标题】:Background color does not show when setting a div height to auto! Why?将 div 高度设置为自动时,背景颜色不显示!为什么?
【发布时间】:2018-07-11 00:44:13
【问题描述】:

当我将其高度设置为自动时,#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;
}

【问题讨论】:

    标签: css html height


    【解决方案1】:

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

    here is your code running

    更多详情请查看w3schools

    希望对你有帮助

    【讨论】:

    【解决方案2】:

    所有元素要么是绝对定位的,要么是浮动的,不会计算父元素的高度。尝试在某些元素或至少在容器上设置最小高度。

    给我一​​点时间,我会尝试设置一个带有解决方案的 jsfiddle :)

    !!!查看lazychio 的答案,这就是您要找的。​​p>

    【讨论】:

      【解决方案3】:

      只需添加溢出:自动;例如在 .css 文件中:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-17
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 2014-08-26
        • 1970-01-01
        • 1970-01-01
        • 2015-01-15
        相关资源
        最近更新 更多