给一个元素一个默认高度,但强制它缩小以适应它的 parent(只有当它达到指定的 min-height 时才允许它溢出)

Give an element a default height, but force it to shrink to fit inside its parent (only allow it to overflow if it hits a specified min-height)

假设我有以下设置:

里面一个parentdiv。

.outer {
  max-height: 200px;
  background-color: green;
}
.inner {
  min-height: 50px;
  /*for demonstration, the default height is set to a value greater than the outer's max-height. Normally, this wouldn't be the case intially */
  height: 250px;
  background-color: pink;
}
<div class="outer">
  <span> Hi!</span>
  <div class="inner"></div>
  <!-- Placing a footer here, only to demonstrate that the content overflows (the background would be green, if it was inside the parent div) -->
  <!-- You can ignore the existence of the footer in your answer -->
  <span> bye! </span>
</div>

关于内容div,我想指定一个默认高度。然而,想象一下 header 文本实际上是一个 div,它的高度可能会动态扩展,将内容向下推。

这最终会导致内容溢出。

我不想让内容溢出,而是希望内部 div 缩小以适应其 parent 的 max-height,直到内部 div 命中它的min-height,那么它就会溢出。

我怎样才能做到这一点?

您可以尝试使用 Flexbox。 Flexbox browser support.

Flexbox 解决方案:

.outer {
    background-color: green;
    display: flex;
    flex-direction: column;
    max-height: 200px;
}

.inner {
    background-color: pink;
    overflow-y: scroll;
}
<div class="outer">
  <span> Header! <br /> <br /> <br /> Line Breaks to demonstrate a tall header.</span>
  <div class="inner"><p>On the content div, I would like to specify a default height. However, imagine that the header text is actually a div, and its height may expand dynamically, pushing the content downwards.</p>
  <p>This will cause the content to overflow eventually.</p>
<p>Rather than having the content overflow, I would like the inner div to shrink to fit within its parent's max-height, until the inner div hits its min-height, then it can overflow.</p> </div>
  <!-- Placing a footer here, only to demonstrate that the content overflows (the background would be green, if it was inside the parent div) -->
  <!-- You can ignore the existence of the footer in your answer -->
  <span> Footer! </span>
</div>