flex布局 项目属性
1. 项目整体伸缩属性
- flex-grow
- 允许放大
- flex-shrink
- 允许收缩
- flex-basis
- 设置item在主轴上的大小(覆盖width属性,但会被 min-width 和 max-width 属性覆盖)
以上属性简写:
flex: 放大因子 收缩因子 大小;
例:flex: 2 2 10rem;
默认值:flex: 0 1 auto; (initial)
1 1 auto = auto
0 0 auto = none
默认效果
flex-grow
- 当容器宽度<=item宽度之和时,每个item宽度一样;
- 当容器宽度足够,即大于item宽度之和时,item按照flex grow factor进行放大
例:flex-grow: 1;
变化如下
CSS
.container>.item {
padding: 1rem;
background-color: lightsteelblue;
border: 1px solid black;
flex-basis: 10rem;
}
.container>.item:first-of-type {
flex-grow: 1;
}
.container>.item:nth-of-type(2) {
flex-grow: 2;
}
.container>.item:nth-of-type(3) {
flex-grow: 3;
}
.container>.item:last-of-type {
flex-grow: 4;
}
flex-shrink
- 当容器宽度足够容纳所有项目时, 不会收缩
- 当容器宽度不够够容纳所有项目时从收缩因子最大的开始收缩
CSS
.container>.item {
padding: 1rem;
background-color: lightsteelblue;
border: 1px solid black;
flex-basis: 10rem;
}
.container>.item:first-of-type {
flex-shrink: 1;
}
.container>.item:nth-of-type(2) {
flex-shrink: 2;
}
.container>.item:nth-of-type(3) {
flex-shrink: 3;
}
.container>.item:last-of-type {
flex-shrink: 4;
}
当容器宽度足够容纳所有项目时:
当容器宽度不够时开始收缩:
下图中,容器总width为 366 < 400, 此时子项目大概宽度:
item1-85, item2-89, item3-92, item4-96
注:容器宽度过小时,会从item3-item1开始逐渐妥协,即item3-item1宽度逐渐与item4相等,最后每个item宽度相等
2. 单独设置某个项目 align-self
.container>.item:nth-of-type(3) {
flex-grow: 3;
align-self: flex-start;
}
3. flex项目支持定位,不支持浮动
.container>.item:nth-of-type(3) {
flex-grow: 3;
align-self: flex-start;
position: absolute;
background-color: blanchedalmond;
left: 5rem;
top: 5rem;
}
4. 改变flex项目顺序
order: value;
数字大靠后排列,数字小靠前排列
.container>.item:nth-of-type(3) {
flex-grow: 3;
order: 20
}
.container>.item:last-of-type {
flex-grow: 4;
order: -1;
}