项目设置属性为 { flex: 1 }时表示的意思

flex属性是 flex-grow  + flex-shrink + flex-basis 的缩写。

1.赋给3个值
.item {
flex: 100 200 300px;
}
// 等价于
.item {
flex-grow: 100;
flex-shrink: 200;
flex-basis: 300px;
}
2.赋值为auto
.item {
flex: auto;
}
//等价于
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: auto;
}
3.赋值为none
.item {
flex: none;
}
// 等价于
.item {
flex-grow: 0;
flex-shrink: 0;
flex-basis: auto;
}
4.赋值为非负数
// 该数字为 flex-grow 值,而flex-shrink 的值取 1,flex-basis 取 0%:

.item {
flex: 1;
}
// 等价于
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;
}
5.赋值为一个长度或百分比
// 将长度或百分比设为 flex-basis 值,而flex-grow 取 1,flex-shrink 取 1

.item1 {
flex: 0%;
}
// 等价于
.item1 {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;
}

// -----------------

.item2 {
flex: 24px;
}
// 等价于
.item2 {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 24px;
}
6.赋值为两个非负数
​// 将两个数字分别设为 flex-grow 和 flex-shrink 的值,而flex-basis 取 0%

.item {
flex: 10 20;
}
// 等价于
.item {
flex-grow: 10;
flex-shrink: 20;
flex-basis: 0%;
}
7.赋值为一个非负数和一个长度或百分比
​​// 将非负数字和 长度或百分比 分别设为 flex-grow 和 flex-basis 的值,flex-shrink 取 1

.item {
flex: 10 100px;
}
// 等价于
.item {
flex-grow: 10;
flex-shrink: 1;
flex-basis: 100px;
}
flex-basis 规定的是子元素的基准值。所以是否溢出的计算与此属性有关。flex-basis 规定的范围取决于 box-sizing。这里主要讨论以下 flex-basis 的取值情况:

auto:首先检索该子元素的主尺寸,如果主尺寸不为 auto,则使用值采取主尺寸之值;如果也是 auto,则使用值为 content。
content:指根据该子元素的内容自动布局。有的用户代理没有实现取 content 值,等效的替代方案是 flex-basis 和主尺寸都取 auto。
百分比:根据其包含块(即伸缩父容器)的主尺寸计算。如果包含块的主尺寸未定义(即父容器的主尺寸取决于子元素),则计算结果和设为 auto 一样。
举一个不同的值之间的区别:

<div class="parent">
<div class="item-1"></div>
<div class="item-2"></div>
<div class="item-3"></div>
</div>
<style type="text/css">
.parent {
display: flex;
600px;
}
.parent > div {
height: 100px;
}
.item-1 {
140px;
flex: 2 1 0%;
background: blue;
}
.item-2 {
100px;
flex: 2 1 auto;
background: darkblue;
}
.item-3 {
flex: 1 1 200px;
background: lightblue;
}
</style>
主轴上父容器总尺寸为 600px
子元素的总基准值是:0% + auto + 200px = 300px,其中
- 0% 即 0 宽度
- auto 对应取主尺寸即 100px
故剩余空间为 600px - 300px = 300px
伸缩放大系数之和为: 2 + 2 + 1 = 5
剩余空间分配如下:
- item-1 和 item-2 各分配 2/5,各得 120px
- item-3 分配 1/5,得 60px
各项目最终宽度为:
- item-1 = 0% + 120px = 120px
- item-2 = auto + 120px = 220px
- item-3 = 200px + 60px = 260px
当 item-1 基准值取 0% 的时候,是把该项目视为零尺寸的,故即便声明其尺寸为 140px,也并没有什么用,形同虚设
而 item-2 基准值取 auto 的时候,根据规则基准值使用值是主尺寸值即 100px,故这 100px 不会纳入剩余空间
————————————————
版权声明:本文为CSDN博主「constantE」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lianfengzhidie/article/details/86679759

原文地址:https://www.cnblogs.com/zhishaofei/p/13266089.html