如何使 div 增长以适应其内容,直至达到 parent 容器的最大大小?

How can I make a div grow to fit its content, up to the max size of the parent container?

我将模态 div 定位在页面中间,max-height 定义为其容器的百分比,在这种情况下,它不应超过页面的 70%身高.

div的内容是两个元素:

我希望模式随内容一起增长,直到 max-height,然后内容 div 应该开始滚动。但是无论我做什么,内容似乎都像这样从模态中溢出:

这是我的标记和样式:

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal {
  max-height: 70%;
  border: 5px dashed green;
  border-radius: 5px;
}

.container {
  /* I cannot remove this container */
  display: flex;
  flex-direction: column;
  width: 600px;
}

.header {
  flex: none;
  background: red;
  height: 100px;
}

.content {
  flex: 1;
  background: yellow;
  overflow: auto;
}

.big-stuff {
  margin: 10px;
  background: orange;
  height: 600px;
}
<div class="modal">
  <div class="container">
    <div class="header">
      Header
    </div>
    <div class="content">
      Content. Should shrink or grow to fit content but only to a max of the container height
      <div class="big-stuff">
        Large content
      </div>
    </div>
  </div>
</div>

不幸的是,我无法更改标记,所以我试图通过修改CSS 来实现它。如果我删除 .container div,那么一切似乎都有效,但我希望有另一种方法。

此处提供完整示例:https://codepen.io/dyancat/pen/QWaOGpB

您可以将 flex 添加到模态,这样内容就不会超出其父级(本例中为模态):

.modal {
    max-height: 70%;
    border: 5px dashed green;
    border-radius: 5px;
    display: flex; /* Add this flex */
}

只需将 css 中的 display:flex 添加到模态 class。

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal {
  max-height: 70%;
  border: 5px dashed green;
  border-radius: 5px;
  display: flex;
}

.container {
  /* I cannot remove this container */
  display: flex;
  flex-direction: column;
  width: 600px;
}

.header {
  flex: none;
  background: red;
  height: 100px;
}

.content {
  flex: 1;
  background: yellow;
  overflow: auto;
}

.big-stuff {
  margin: 10px;
  background: orange;
  height: 600px;
}
<div class="modal">
  <div class="container">
    <div class="header">
      Header
    </div>
    <div class="content">
      Content. Should shrink or grow to fit content but only to a max of the container height
      <div class="big-stuff">
        Large content
      </div>
    </div>
  </div>
</div>