使div的高度随其内容扩展

新手上路,请多包涵

我有这些嵌套的 div,我需要扩展主容器(在高度上)以容纳内部的 DIV

     <!-- head -->
    ...
    <!-- /head -->

    <body class="main">
      <div id="container">
        <div id="header">
          <!--series of divs in here, graphic banner etc. -->
        </div>

    <div id="main_content"> <!-- this DIV _should_ stretch to accommodate inner divs -->
      <div id="items_list" class="items_list ui-sortable">
        <div id="item_35" class="item_details">
        </div>
        <div id="item_36" class="item_details">
        </div>
        <div id="item_37" class="item_details">
        </div>
        <!-- this list of DIVs "item_xx" goes on for a while
             each one representing a photo with name, caption etcetc -->
      </div>
    </div>
    <br class="clear"/>

    <div id="footer">
    </div>
  </body>
</html>

CSS 是这样的:

 * {
    padding: 0;
    margin: 0;
}

.main {
    font: 100% Verdana, Arial, Helvetica, sans-serif;
    background: #4c5462;
    margin: 0;
    padding: 0;
    text-align: center;
    color: #000000;
}
.main #container {
    height: auto;
    width: 46em;
    background: #4c5462;
    margin: 0 auto;
    border: 0px solid #000000;
    text-align: left;
}

.main #main_content {
    padding: 5px;
    margin: 0px;
}
#items_list {
    width: 400px;
    float: left;
}

.items_list {
    width: 400px;
    float: left;
}
.item_details {
    margin-top: 3px;
    margin-bottom: 3px;
    padding: 3px;
    float: left;
    border-bottom: 0.5px solid blue;
}

我遇到的问题是 #main_content 不会拉伸以容纳所有内部 div,结果它们一直在背景中移动。

考虑到上述情况,我该如何解决这个问题?

原文由 patrick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 356
2 个回答

您需要在关闭 #main_content div 之前强制执行 clear:both 。我可能会将 <br class="clear" />; 移动到 #main_content div 并将 CSS 设置为:

 .clear { clear: both; }

更新: 这个问题仍然有相当多的流量,所以我想用一个现代的替代方法更新答案,使用 CSS3 中称为 Flexible boxes 或 Flexbox 的新布局模式

 body {
  margin: 0;
}

.flex-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

header {
  background-color: #3F51B5;
  color: #fff;
}

section.content {
  flex: 1;
}

footer {
  background-color: #FFC107;
  color: #333;
}
 <div class="flex-container">
  <header>
    <h1>
     Header
    </h1>
  </header>

  <section class="content">
    Content
  </section>

  <footer>
    <h4>
      Footer
    </h4>
  </footer>
</div>

大多数现代浏览器目前都支持 Flexboxviewport units ,但如果您必须保持对旧浏览器的支持,请确保检查特定浏览器版本的兼容性。

原文由 jennyfofenny 发布,翻译遵循 CC BY-SA 3.0 许可协议

试试这个: overflow: auto;

它适用于我的问题..

原文由 sipőcz péter 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题