使 HTML 元素展开以适合内容

Make HTML Element Expand To Fit Content

我正在编写一个网络应用程序,主要是在 AngularJS 中使用 CSS 的 flexbox 进行某些布局,如果这很重要的话。在过去的几个小时里,我一直在发疯,试图解决我目前遇到的问题。

我 运行 遇到的问题如下: 页面上有两个并排的 div。最左边的 div 是一个菜单,它必须始终是文档内容或浏览器 window 的高度(以较大者为准)。最右边的 div 是动态附加内容的那个。当程序启动时,最右边的 div 小于浏览器的高度 window (因为它没有太多内容)但是随着应用程序的进行,内容被添加到它最终是比浏览器长得多 window.

可以找到显示问题的 JSFiddle by clicking here

fiddle 的 HTML 结构大部分是固定的(可以添加容器但不应删除),因为这是对具有相同基本结构的复杂应用程序的极大简化。此外,我将所有 CSS 高度设置为 100% 仅仅是因为阅读了另一个答案,而不是因为我知道他们需要完成这项工作(我确实希望菜单以全屏方式开始,即使内容很少,但是).

黑色 div 代表菜单,黄色 div 代表包含内容的菜单。单击 "click me to add content" 按钮时,100 行内容将附加到内容 div 上,然后使其比 window 更长。期望的效果是黄色和黑色 div 都展开,使得黄色 div 与容纳内容所需的一样大,而黑色 div 是相同的高度为黄色div。相反,当添加内容时,发生的事情(如您所见)既不是黑色也不是黄色 div 扩展,内容只是流出黄色 div.[=35 的边界=]

我已经在 Whosebug 和其他地方尽我最大的能力研究了这个问题,但似乎没有任何解决方案适用于这种类型的动态内容(尽管我可能遗漏了一些东西)。 this one and this one recommend using the min-height property on some elements but when I tried it, the black and yellow divs started small (size of the content, not the full browser height) but did expand correctly. Basically, when I try other people's solutions, it appears that I can either have divs that start out small (less than full screen) and grow correctly or start out correctly (full screen, even though initial content is smaller) and don't grow but not both (I would like divs that start out correctly and grow to fit content). Additionally, answers such as this one 这样的答案建议 min-heightheight 的组合来实现一种效果或另一种效果,但不是我正在寻找的两者。

如果能得到任何帮助,我将不胜感激,感谢您抽出宝贵时间。

编辑:

删节版,适合赶时间的人。

我希望能够让两个并排 div 开始时占据浏览器的整个高度 window 即使其中没​​有内容。然后,当向其中一个 div 添加足够的内容使其大于浏览器时,两个 div 都会扩展以适应可用内容。 JSFiddle 在 this link 可用。 fiddle 的问题是当按下添加新内容按钮时,黄色和黑色 div 不会扩展以适应新内容。

您可以使用 display:table-cell 来实现这一点。请检查 JSfiddle.

使用 flexbox 我想出了这个似乎符合您最初标准的结构。

我在Codepen中添加了一个demo,加了个特高'extender'div,这样你可以看到添加很多内容后的效果。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html,
body {
  min-height: 100%;
}
.wrapper {
  display: flex;
  flex-direction: column;
  border: 1px solid red;
  min-height: 100vh;
}
main {
  flex-grow: 1;
  border: 1px solid red;
  height: 100%;
  display: flex;
}
.left {
  width: 200px;
  background: lightblue;
  flex: none;
}
.right {
  flex-grow: 1;
  background: salmon;
}
<div class="wrapper">
  <main>
    <div class="col left">
      <h3>Fixed Left</h3>
    </div>
    <div class="col right">
      <h3>Flexible Right</h3>
    </div>
  </main>
</div>

尝试解决这个问题中的 CSS - - 我能够让你的示例正常工作,同时大大简化了你的 CSS。

诀窍似乎是在 body 元素处开始 flexing,并告诉容器增长,但永不收缩:

body {
    display: flex;
    flex-direction: column;
}

.container, .subContainer {
    display: flex;
    flex-direction: row;
    flex-shrink: 0;
    flex-grow: 1;
}

使用完整代码更新了 JSFiddle(不需要 <div class="subContainer">,如果您不需要它用于其他用途,可以将其删除):http://jsfiddle.net/aej8na8q/38/