gpt4 book ai didi

CSS flex 基础 : 0% has different behaviour to flex-basis: 0px

转载 作者:行者123 更新时间:2023-12-05 02:50:49 24 4
gpt4 key购买 nike

根据 MDN , flex: 1 简写应该设置为 flex-basis: 0。然而,它实际上设置了 flex-basis: 0%,更令人惊讶的是它有不同的行为。

在下面的示例中,我希望 div.middle 能够收缩和滚动,因为它被赋予了 overflow-y: autoflex: 1,这也意味着 flex-basis: 0。但它并没有——整个 body 都在滚动,因为它拒绝收缩。如果您取消注释显式 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

最佳答案

问题与百分比的使用有关。使用 00px 是微不足道的,因为您将初始高度设置为 0 然后元素将增长以填充剩余空间。

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

Percentages: relative to the flex container’s inner main size 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>

Why does flex: 1 set flex-basis: 0% instead of flex-basis: 0?

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

关于CSS flex 基础 : 0% has different behaviour to flex-basis: 0px,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63475073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com