我有一个overflow:auto 在嵌套的“圣杯式”弹性盒布局中。 overflow:auto 行为适用于 2 级和 3 级嵌套。
您的2-level 代码确实在 Chrome 和 IE11 中按预期工作。但是,它在 Firefox 中失败。与您的 3-level 代码相同:适用于 Chrome 和 IE11,但不适用于 Firefox。
但是,一旦我进入 4 级嵌套,它就会“中断”,要求我指定 min-height:0 属性(尽管我一直通过 flex:1 指定 flex-basis:0,这应该取消 flex-basis:content/内容大小
默认)。 为什么这只发生在 4 级嵌套?
再一次,您的说法适用于 Chrome 和 IE11,但不适用于 Firefox。
解决方案
让我们从修复开始,以便所有演示都可以在 Chrome、Firefox 和 IE11 中运行。 (我没有在 Safari 中测试过,但那是像 Chrome 一样的 WebKit,所以用vendor prefixes for any versions prior to 9 应该没问题。)
另外,我将在答案中使用编译后的代码,因为不是每个人都使用预处理器。
Revised 2-level(加了两行代码)
.violet {
flex: 1;
background: violet;
display: flex;
flex-direction: column;
min-height: 0; /* new */
min-width: 0; /* new */
}
Revised 3-level(加了四行代码)
.violet {
flex: 1;
background: violet;
display: flex;
flex-direction: column;
min-height: 0; /* new */
min-width: 0; /* new */
}
.orange {
flex: 1;
background: orange;
display: flex;
min-height: 0; /* new */
min-width: 0; /* new */
}
Revised 4-level(加了一行代码)
.violet {
flex: 1;
background: violet;
display: flex;
flex-direction: column;
/* For some reason this is not needed */
/* min-height:0; */
min-width: 0; /* new */
}
分解行为
你的嵌套有很多事情要做。我不会逐行调试代码,但我会提供三个可能对您有用的概念。
1.计算百分比高度
Chrome、Firefox 和 IE11 可以对元素的高度有不同的解释。
这是规范中所说的:
CSS height property
百分比
指定百分比高度。该百分比是相对于生成框的包含块的高度计算的。如果没有明确指定包含块的高度并且该元素不是绝对定位的,则该值计算为“auto”。
auto
高度取决于其他属性的值。
传统上,在计算百分比高度时,浏览器会将规范中使用的术语“高度”解释为 height 属性的值。
基于对height 定义的解读,可以很容易地解释为computed height,但height 属性要求已成为主要实现。在处理百分比高度时,我从未见过 min-height 或 max-height 在父母身上工作。
Chrome 期望在计算高度时看到 height 属性。如果不是,它将计算高度为auto。然而,Firefox 对该规范有更广泛的解释。它也接受弹性高度(如 here 和 here 和 here 所证明的那样)。
尚不清楚哪些浏览器更合规。
height 属性定义自 1998 年以来一直没有更新 (CSS2),这无济于事。
在您的所有三个演示中,您都结合了百分比高度、像素高度和弹性高度。在对代码进行故障排除时,您可能希望牢记不同的浏览器解释。
这里有更多细节:Working with the CSS height property and percentage values
2. Why doesn't flex item shrink past content size?
3. flex-basis: 0 与 flex-basis: auto
flex: 1 1 auto(或简称flex: auto)根据内容大小或高度属性调整弹性项目的大小。
flex: 1 1 0(或简称flex: 1)根据弹性容器中的可用空间调整弹性项目的大小。
每个可能对overflow: auto 的行为产生不同的影响。
更多详情:Page-filling flexbox layout with top and side bars not quite working