【问题标题】:CSS flex-basis: 0% has different behaviour to flex-basis: 0pxCSS flex-basis: 0% 与 flex-basis: 0px 有不同的行为
【发布时间】:2020-12-08 00:28:00
【问题描述】:

根据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 中。

标签: css flexbox


【解决方案1】:

这个问题与百分比的使用有关。使用00px 很简单,因为您将初始高度设置为0,然后元素将增长以填充剩余空间。

使用N% 是另一回事,因为在这种情况下,您将初始高度设置为基于父高度。

百分比:相对于弹性容器的内部主要尺寸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?

检查这个:What does flex: 1 mean? 并非所有浏览器都将flex:1 设置为等于flex:1 1 0

【讨论】:

  • spec 明确指出“当从 flex 简写中省略时,其指定值为 '0'”。为什么浏览器违反规范并设置为 0%?
  • @SystemParadox 因为遵循规范从来都不是义务。某些浏览器会有意或无意地做出不同的处理方式(我们称之为bug
  • 进一步证明@TemaniAfif 确实是正确的:如果我们将min-height: 100%; 更改为height: 100%;,事情会按预期工作(即flex-basis: 0% 的行为类似于flex-basis: 0
  • 尊敬的先生,您是个天才。就是这样????????
猜你喜欢
  • 1970-01-01
  • 2013-12-06
  • 2018-05-14
  • 2016-09-18
  • 2021-08-10
  • 2021-10-29
  • 2016-05-27
  • 2015-03-23
  • 2023-01-28
相关资源
最近更新 更多