Flex
基础
flex-row
扩张,宽度总和 < 容器宽度flex-shrink
收缩,宽度总和 > 容器宽度flex-basis
auto
使用子元素的尺寸0
子元素宽度为0
flex-grow | flex-shrink | flex-basis | |
---|---|---|---|
默认 | 0 | 1 | auto |
none | 0 | 0 | auto |
auto | 1 | 1 | auto |
n(非负) | n | 1 | 0% |
长度或百分比 | 1 | 1 | 长度或百分比 |
n,m(非负) | n | m | 0 |
n,长度或百分比 | n | 1 | 长度或百分比 |
flex:1
不管内容多少,一般都是平分空间,空间大小都一致flex:auto
是根据内容的大小来分,不是平的(除非内容都是一样,才平分)
计算
- 各个子元素根据 flex-basis 的值,填充父元素
- 根据填充后的剩余空间大小根据flex-grow和flex-shrink伸缩
flex-grow
vue
<template>
<div class="parent">
<div class="item-1">64px</div>
<div class="item-2">104px</div>
<div class="item-3">132px</div>
</div>
</template>
<style lang="scss" scoped>
.parent {
display: flex;
width: 300px;
div {
height: 100px;
line-height: 100px;
text-align: center;
color: #fff;
}
.item-1 {
width: 40px;
flex: 2 1 0%;
background: theme('colors.yellow.800');
}
.item-2 {
width: 40px;
flex: 2 1 auto;
background: theme('colors.yellow.500');
}
.item-3 {
flex: 1 1 100px;
background: theme('colors.yellow.300');
}
}
</style>
64px
104px
132px
- 剩余空间 = 300 - 0 - 40 - 100 = 160
- 等分:2+2+1=5
- item-1 = 0 + 2/5 * 160 = 64
- item-2 = 40 + 2/5 * 160 = 104
- item-3 = 100 + 1/5 * 160 = 132
flex-shrink
vue
<template>
<div class="parent">
<div class="item-1"></div>
<div class="item-2"></div>
<div class="item-3"></div>
</div>
</template>
<style lang="scss" scoped>
.parent {
display: flex;
width: 300px;
div {
height: 100px;
line-height: 100px;
text-align: center;
color: #fff;
}
.item-1 {
width: 100px;
flex: 2 1 0%;
background: theme('colors.yellow.800');
}
.item-2 {
width: 200px;
flex: 2 1 auto;
background: theme('colors.yellow.500');
}
.item-3 {
flex: 1 1 360px;
background: theme('colors.yellow.300');
}
}
</style>
- 溢出空间 = 0 + 200 + 360 - 300 = 260
- 权重:1*0 + 1*200 + 1*360 = 560
- item-1 = 0
- item-2 = 200 - (1*200)/560 * 260 = 107.14
- item-3 = 360 - (1*360)/560 * 260 = 192.86
参考
- Flexbox - MDN
- flex - MDN
- flex 布局的基本概念 - MDN
- align-items和align-content的区别 - 掘金文章