CSS 中 flex-basis: 0% 和 flex-basis: 0px 的行为不同

4
根据MDNflex: 1缩写应该设置flex-basis: 0。然而,它实际上设置了flex-basis: 0%,更令人惊讶的是这具有不同的行为。
在下面的示例中,我期望div.middle收缩并滚动,因为它被赋予了overflow-y: autoflex: 1,这也应意味着flex-basis: 0。但它没有 - 整个主体滚动,因为它拒绝缩小。如果取消注释显式的flex-basis: 0,则它将正常工作。

body {
  text-align: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: 0;
}
.outer {
  min-height: 100%;
  display: flex;
  background: #99f;
  flex-direction: column;
}
.middle {
  background: #f99;
  flex: 1;
  /*flex-basis: 0;*/
  overflow-y: auto;
}
<div class='outer'>
  <div class='top'>top</div>
  <div class='middle'>
    A
    <div style='height:800px'></div>
    B
  </div>
  <div class='bottom'>bottom</div>
</div>

我在Chrome 84.0和Firefox 68.11.0esr中测试了这个,它们都有相同的意外行为。

  1. 为什么flex-basis: 0%flex-basis: 0不同?
  2. 为什么flex: 1会设置flex-basis: 0%而不是flex-basis: 0

太好了!这种非预期的行为在 Firefox 90 和 Chrome 91 中仍然存在。 - LGenzelis
1个回答

5
问题与百分比的使用有关。使用00px很简单,因为您将把初始高度设置为0,然后元素将增长以填充剩余空间。
使用N%则不同,因为在这种情况下,您正在基于父元素的高度设置初始高度。

百分比:相对于 flex 容器的内部主轴尺寸ref

在您的情况下,flex 容器没有任何显式大小,因为您仅使用了min-height定义,因此我们无法解析百分比值,它将失败为auto 如果您将最小高度更改为高度,则两者的行为将相同:

body {
  text-align: center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: 0;
}
.outer {
  height: 100%;
  display: flex;
  background: #99f;
  flex-direction: column;
}
.middle {
  background: #f99;
  flex: 1;
  /*flex-basis: 0;*/
  overflow-y: auto;
}
<div class='outer'>
  <div class='top'>top</div>
  <div class='middle'>
    A
    <div style='height:800px'></div>
    B
  </div>
  <div class='bottom'>bottom</div>
</div>

为什么flex:1会设置flex-basis: 0%而不是flex-basis: 0?

请查看此链接:flex:1的含义是什么? 并非所有浏览器都将flex:1设置为等于flex:1 1 0


规范明确指出:“当从 flex 简写中省略时,其指定值为 '0'”。为什么浏览器违反规范并设置为 0%? - SystemParadox
@SystemParadox 因为遵循规范从来不是一项义务。有些浏览器会故意或者错误地采取不同的做法(我们称之为“漏洞”)。 - Temani Afif
进一步证明@TemaniAfif是正确的:如果我们将min-height: 100%;更改为height: 100%;,则事情会按预期工作(即,flex-basis: 0%的行为类似于flex-basis: 0 - LGenzelis
亲爱的先生,您是天才。就这些。 - vipulbhj
@TemaniAfif,我来晚了,但是:你能告诉我auto回退的具体规定在哪里吗?谢谢! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接