为什么这个 flex item 有高度限制?

Why does this flex item have its height limited?

我偶然发现了一些发生在我的 flex 子项上的事情,如 this JSFiddle 中所示。

这是代码:

<div style="position:absolute; top:10px; left:10px; background-color:yellow; height:50px; width:200px; display:flex; flex-direction:column;">
    <div style="overflow:hidden;">inner div text<br>inner div text<br>inner div text<br>inner div text<br>inner div text</div>
</div>

<div style="position:absolute; top:10px; left:250px; background-color:green; height:50px; width:200px;">
    <div style="overflow:hidden;">inner div text<br>inner div text<br>inner div text<br>inner div text<br>inner div text</div>
</div>

<div style="position:absolute; top:200px; left:100px; border:1px solid black; height:300px; width:300px; overflow:hidden;">
    <div style="overflow:hidden;">
        Why does the inner div on the yellow left have its height limited to that of its container, but not the inner div on the green right?  As far as I can tell there are 4 things combined that trigger this:<br>1) the container has position:absolute<br>
        2) the container has a fixed height/width<br>
        3) the container is flexbox<br>
        4) the flex item has overflow:hidden<br><br>But I can't find anything exactly in the flexbox spec to cause this behaviour.  Why is it happening?
    </div>
</div>

基本上,当 overflow:hidden 设置时,具有固定高度的 flexbox 容器内的 flex 项目将其高度限制为 flexbox 容器的高度。另一方面,固定高度的非弹性容器内的等效 div 只会扩展到其内容的大小。

flexbox 规范中的何处指定了此行为?这只是浏览器的怪癖吗?这似乎不太可能发生在 Firefox、Chrome 和 IE 中。假设它是定义明确的 flexbox 行为,我想确切地知道它是如何以及何时被触发的。另请注意,当您从 child(不是容器)中删除 overflow:hidden 时,它的高度将不再受到限制。

好的,我想我知道发生了什么。

直到 flexbox,如果不显式设置其 width/height,就无法使元素小于其内容的大小。使用 flexbox,还有第二种方法。

Para 9.11 的 flexbox 规范讨论了如何计算弹性项目的交叉尺寸。基本上,如果弹性项目设置了 align-self: stretch(在我的例子中它确实如此),它将尝试填充容器的弹性线(在我的例子中是垂直线,即高度)。这是隐式设置弹性项目的高度,而不是显式使用 height 属性。容器本身也需要有一个确定的高度,才能传递给弹性项目(在我的示例中,容器的高度是通过 height CSS 属性明确设置的,我想最终需要在链中的某个点完成)。

但是需要满足两个条件:浏览器需要想要调整项目的大小,项目需要可调整大小.

为了让浏览器想要调整项目的大小,它需要是一个弹性项目,满足上面提到的横向尺寸条件(最终可能决定它的宽度或高度)由浏览器根据其容器的横向尺寸计算。

要使项目 resizable 在此上下文中,它需要 notflex-shrink 设置为 0(请注意,flex:none 是 shorthand,用于将 flex-shrink 设置为 0,除此之外),并设置 overflow:hidden(大概给浏览器 "permission" 调整弹性项目的大小,使其内容比它大,并隐藏)。只有这样,浏览器才会真正调整弹性项目本身的大小。

这与 flexbox 模型之外发生的行为明显不同,其中固定 height/width 容器的子容器可能具有内容 clipped,但它会保留容纳其内容的必要大小。部分内容只会被隐藏。在这里,弹性项目确实(可能)被调整为小于其内容,这具有非常重要的意义(特别是如果您希望子元素的内容具有滚动条)。