介绍
Flex(Flexible Box)是一种用于布局的 CSS 方式,能够方便地实现元素在容器中的 自动调整大小、对齐、换行 等功能,特别适用于响应式设计。
启用 flex 布局
要使用 Flex 布局,必须先在父容器上设置:
1
2
3
|
.container {
display: flex;
}
|
flex 容器(父级)属性
属性 |
作用 |
display: flex |
启用 flex 布局,使子元素变成弹性 |
flex-direction |
设定主轴方向(row、column) |
flex-wrap |
设定子元素是否换行(wrap、nowrap) |
justify-content |
控制主轴上的对齐方式(居中、均分) |
align-items |
控制交叉轴上的对齐方式 |
align-content |
控制多行弹性项的对齐方式 |
flex-direction(主轴方向)
决定主轴的方向,默认值是 row(从左到右)。
1
2
3
4
5
6
|
.container {
flex-direction: row; /* 从左到右 (默认) */
flex-direction: row-reverse; /* 从右到左 */
flex-direction: column; /* 从上到下 */
flex-direction: column-reverse; /* 从下到上 */
}
|
flex-wrap(是否换行)
1
2
3
4
5
|
.container {
flex-wrap: nowrap; /* 默认值,不换行 */
flex-wrap: wrap; /* 换行 */
flex-wrap: wrap-reverse; /* 反向换行 */
}
|
justify-content(主轴对齐方式)
1
2
3
4
5
6
7
8
|
.container {
justify-content: flex-start; /* 默认,左对齐 */
justify-content: flex-end; /* 右对齐 */
justify-content: center; /* 居中 */
justify-content: space-between; /* 两端对齐,中间平均分布 */
justify-content: space-around; /* 每个元素两侧间距相等 */
justify-content: space-evenly; /* 每个元素之间间距相等 */
}
|
align-items(交叉轴对齐方式)
1
2
3
4
5
6
7
|
.container {
align-items: flex-start; /* 顶部对齐 */
align-items: flex-end; /* 底部对齐 */
align-items: center; /* 垂直居中 */
align-items: baseline; /* 文字基线对齐 */
align-items: stretch; /* 高度自动拉伸(默认) */
}
|
align-content(多行对齐方式)
适用于 flex-wrap: wrap 的多行情况
1
2
3
4
5
6
7
8
|
.container {
align-content: flex-start; /* 多行从顶部开始 */
align-content: flex-end; /* 多行从底部开始 */
align-content: center; /* 多行居中 */
align-content: space-between; /* 两端对齐 */
align-content: space-around; /* 每行两侧间距相等 */
align-content: stretch; /* 让所有行填充整个容器(默认) */
}
|
Flex 子项(子元素)属性
属性 |
作用 |
flex-grow |
控制元素放大比例(默认 0,不放大) |
flex-shrink |
控制元素缩小比例(默认 1,允许缩小) |
flex-basis |
设定元素初始大小 |
flex |
flex-grow, flex-shrink, flex-basis 的缩写 |
align-self |
控制单个元素在交叉轴上的对齐方式 |
flex-grow(放大比例)
决定了元素在 有剩余空间 时如何分配:
1
2
3
4
5
|
.item {
flex-grow: 0; /* 不放大(默认值) */
flex-grow: 1; /* 均分剩余空间 */
flex-grow: 2; /* 该元素会占据 2 份空间 */
}
|
flex-shrink(缩小比例)
决定了元素在 空间不足 时如何缩小:
1
2
3
4
|
.item {
flex-shrink: 1; /* 默认值,允许缩小 */
flex-shrink: 0; /* 不允许缩小 */
}
|
flex-basis(初始大小)
用于设定元素的初始大小(类似 width,但受 flex-grow 影响):
1
2
3
4
|
.item {
flex-basis: auto; /* 默认,取决于内容大小 */
flex-basis: 100px; /* 初始宽度 100px */
}
|
flex(简写属性)
等价于 flex-grow flex-shrink flex-basis:
1
2
3
4
5
|
.item {
flex: 1; /* 等价于 flex: 1 1 0%; */
flex: 2; /* 等价于 flex: 2 1 0%; */
flex: 1 0 auto; /* 允许放大,不缩小,大小取决于内容 */
}
|
align-self(单个子项的对齐方式)
单独调整某个子项的 align-items:
1
2
3
4
5
6
|
.item {
align-self: flex-start; /* 顶部对齐 */
align-self: flex-end; /* 底部对齐 */
align-self: center; /* 居中对齐 */
align-self: stretch; /* 拉伸填充 */
}
|