Flex 布局详解
Flex 布局(Flexible Box Layout)是 CSS3 中一种现代的布局方式,它提供了一种更有效的方式来对容器中的项目进行排列、对齐和分配空间,即使它们的大小是未知或动态的。
[万字长文]一文教你彻底搞懂flex布局_flex 分行-CSDN博客
一、Flex 布局基本概念
Flex 布局由**弹性容器(Flex Container)和弹性项目(Flex Items)**组成:
- Flex Container(弹性容器):通过设置
display: flex 或 display: inline-flex 的元素
- Flex Items(弹性项目):弹性容器的直接子元素
二、Flex 容器属性
1. display
定义容器使用 Flex 布局:
1 2 3 4
| .container { display: flex; display: inline-flex; }
|
2. flex-direction
决定主轴方向(项目的排列方向):
1 2 3 4 5 6
| .container { flex-direction: row; flex-direction: row-reverse; flex-direction: column; flex-direction: column-reverse; }
|
3. flex-wrap
定义项目是否换行:
1 2 3 4 5
| .container { flex-wrap: nowrap; flex-wrap: wrap; flex-wrap: wrap-reverse; }
|
4. flex-flow
flex-direction 和 flex-wrap 的简写:
1 2 3
| .container { flex-flow: row nowrap; }
|
5. 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; }
|
6. align-items
定义项目在交叉轴上的对齐方式:
1 2 3 4 5 6 7
| .container { align-items: stretch; align-items: flex-start; align-items: flex-end; align-items: center; align-items: baseline; }
|
7. align-content
定义多根轴线的对齐方式(只有一根轴线时无效):
1 2 3 4 5 6 7 8
| .container { align-content: stretch; align-content: flex-start; align-content: flex-end; align-content: center; align-content: space-between; align-content: space-around; }
|
三、Flex 项目属性
1. order
定义项目的排列顺序,数值越小越靠前:
2. flex-grow
定义项目的放大比例(剩余空间分配):
1 2 3
| .item { flex-grow: 0; }
|
3. flex-shrink
定义项目的缩小比例(空间不足时):
1 2 3
| .item { flex-shrink: 1; }
|
4. flex-basis
定义项目在分配多余空间之前的主轴尺寸:
1 2 3 4
| .item { flex-basis: auto; flex-basis: 100px; }
|
5. flex
| 写法 |
等价于 |
效果 |
flex: 1 |
flex: 1 1 0% |
完全按比例分配空间 |
flex: auto |
flex: 1 1 auto |
考虑项目自身尺寸后再分配剩余空间 |
flex: none |
flex: 0 0 auto |
不放大不缩小,保持原有尺寸 |
flex: initial |
flex: 0 1 auto |
默认值,可缩小但不放大 |
flex-grow, flex-shrink 和 flex-basis 的简写:
1 2 3 4 5
| .item { flex: none; flex: auto; flex: 1; }
|
6. align-self
允许单个项目有与其他项目不同的对齐方式:
1 2 3 4 5 6 7 8
| .item { align-self: auto; align-self: flex-start; align-self: flex-end; align-self: center; align-self: baseline; align-self: stretch; }
|
四、Flex 布局常见应用场景
1. 水平垂直居中
1 2 3 4 5
| .container { display: flex; justify-content: center; align-items: center; }
|
2. 等分布局
1 2 3 4 5 6
| .container { display: flex; } .item { flex: 1; }
|
3. 圣杯布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| .container { display: flex; flex-direction: column; } .header, .footer { height: 60px; } .content { display: flex; flex: 1; } .main { flex: 1; } .aside { width: 200px; }
|
4. 流式布局
1 2 3 4 5 6 7
| .container { display: flex; flex-wrap: wrap; } .item { width: 25%; }
|
五、Flex 布局注意事项
- Flex 布局对浮动(float)、清除浮动(clear)和垂直对齐(vertical-align)无效
- 某些旧版浏览器需要前缀(-webkit-、-moz-等)
- 嵌套 Flex 容器时要注意性能问题
- 移动端对 Flex 布局支持良好,是移动端布局的首选方案
Flex 布局极大地简化了复杂布局的实现,是现代 Web 开发中必不可少的布局技术。掌握 Flex 布局可以让你更高效地创建响应式、灵活的页面结构。