Chrome中的Flexbox--如何限制嵌套元素的大小?

Flexbox in Chrome--How to limit size of nested elements?

在 Google Chrome 中,我如何强制一个元素嵌套在 flexbox 的一个成员中("member of a flexbox" 我的意思是 child 样式化的元素使用 display:flex) 将其大小限制为嵌套在其下的 flexbox 成员的大小?例如,假设我有以下内容:

<div style="display:flex; flex-direction:column; height:100vh;">
  <div style="height:60px;">Static header</div>
  <div style="flex: 1 1 0; overflow:hidden;">
     <div style="overflow:auto; height:100%;" id="problem-is-here">
       Lots and lots of content, way too much to fit in the viewport
     </div>
  </div>
</div>

因为第一个 child div 最外层 div 的高度是恒定的,它最终正好是 60px 高,并且因为第二个 child divflex-grow 为 1,它获得剩余的 space 可用(在本例中,视口的 100% 减去 60px)。我可以确认此元素的尺寸根据 Inspect Element 刚好足以占据视口的其余部分 space.

在 Firefox 和 IE11 中,由于 height:100%,最里面的元素 (id="problem-is-here") 会采用为其 parent 计算的高度。因此,由于它太小而无法显示其内容并且 overflow 设置为 auto,因此它(而不是整个 body)获得一个垂直滚动条。这就是我要的。

然而,在 Chrome 中,最里面的元素以足够的高度呈现以包含其所有内容,这比其 parent 的高度更高。因此,因为它的 parent 有 overflow:hidden,所以没有滚动条出现并且无法访问多余的内容。当 parent 高度由 flexbox 而不是 CSS 决定时,我如何告诉 Chrome 渲染这个最里面的元素,其高度最多等于它的 parent height属性?请注意,我不能给最里面的 div 或其 parent 一个确定的 height 值,因为在我正在处理的应用程序中,其他 flexbox 成员的数量可能会有所不同。

注意:我尝试了其他答案的一些建议,例如将所有元素设置为 min-height:0 而不是 auto,或者确保 flex-basis 设置为 0,但其中 none 个有效。参见

http://plnkr.co/edit/UBRcrNmR5iDbn3EXu6FI?p=preview

举个例子说明问题。 (id 为 heres-the-problemdiv 是我希望其高度限制在其 parent 高度的那个。)

首先,让我们来了解一下术语:

...how do I force an element nested inside of a member of a flexbox (by "member of a flexbox" I mean a child of an element styled with display:flex) to limit its size to the size of the flexbox member it's nested under?

具有 display: flex 的元素称为 flex 容器(技术上)或 flex parent(口语化)。

弹性容器的子项称为 弹性项目。注意 children 这个词(第一级)。弹性容器的子项以外的后代不是弹性项目,大多数弹性属性不适用于它们。


现在,解决您的问题:

问题是 Firefox(显然还有 IE11)对百分比高度规则的解释与 Chrome 不同。

具体来说,您想要的垂直滚动条未在 Chrome 中呈现,因为您使用百分比高度的方式不符合 spec 的传统实现方式。

CSS height property

percentage
Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly and this element is not absolutely positioned, the value computes to "auto".

auto
The height depends on the values of other properties.

换句话说,如果您希望元素具有百分比高度,则必须在包含块(即父级)上指定高度。

在您的代码中,body(级别 1)有 height: 100vh

向下一级,.max-flex(第 2 级)有 height: 100%

向下四层,.large-nested-div(第 4 层)有 height: 100%

然而,在.variable-flex-content(级别3),没有height 属性。您正在使用 flex: 1 1 0 定义高度。就 Chrome 而言,这是链中缺失的 link 并且违反了规范。 Chrome 期望看到 height 属性,如果没有,它将计算高度 auto.


Chrome vs Firefox(我没有测试过IE11,这里就不提了)

传统上,在计算百分比高度时,浏览器将规范对术语 "height" 的使用解释为表示 height 属性 的值。它可以很容易地解释为高度(通用术语),但 height 属性 要求已成为主要实现。在处理百分比高度时,我从未见过 min-heightmax-height 在父级上工作。

然而,最近,如本问题和 and 中所述,Firefox 已扩大其解释以接受 flex 高度。

尚不清楚哪个浏览器更兼容。

height 属性 定义自 1998 年以来一直未更新 (CSS2),这无济于事。


解决方案

不要用 flex: 1 1 0% 定义 .variable-flex-content 的高度,请尝试使用 height: 100%height: calc(100% - 60px).