Flex帮助文档怎么用?,Flex入门教程有哪些?
- 云服务器
- 2026-07-24
- 7
基本概念
Flexbox(弹性盒子)是一种 CSS 布局模型,专为一维布局设计,能高效地分配容器内项目的空间,并控制它们的对齐方式,要使用 Flexbox,需要将容器元素的 display 属性设置为 flex 或 inline-flex。
容器属性
以下属性作用于 Flex 容器(父元素):

| 属性 | 值 | 说明 |
|---|---|---|
| flex-direction | row / row-reverse / column / column-reverse | 定义主轴方向,默认 row(水平从左到右) |
| flex-wrap | nowrap / wrap / wrap-reverse | 项目是否换行,默认 nowrap |
| justify-content | flex-start / flex-end / center / space-between / space-around / space-evenly | 主轴上的对齐方式 |
| align-items | stretch / flex-start / flex-end / center / baseline | 单行交叉轴对齐方式,默认 stretch |
| align-content | flex-start / flex-end / center / space-between / space-around / stretch | 多行交叉轴对齐方式,仅在 flex-wrap: wrap 时生效 |
主轴与交叉轴
- 主轴:由 flex-direction 决定的方向。
- 交叉轴:垂直于主轴的方向。
项目属性
以下属性作用于 Flex 项目(子元素):
| 属性 | 值 | 说明 |
|---|---|---|
| order | <integer> | 项目的排列顺序,值越小越靠前,默认 0 |
| flex-grow | <number> | 放大比例,默认 0(不放大) |
| flex-shrink | <number> | 缩小比例,默认 1(可缩小) |
| flex-basis | <length> / auto | 项目在分配多余空间前的初始大小,默认 auto |
| flex | none / [flex-grow] [flex-shrink] [flex-basis] | 简写属性,推荐使用 flex: 1 等常见写法 |
| align-self | auto / flex-start / flex-end / center / baseline / stretch | 单独设置某个项目的交叉轴对齐方式,覆盖 align-items |
常见简写示例
- flex: 1 等价于 flex-grow: 1; flex-shrink: 1; flex-basis: 0%
- flex: auto 等价于 flex-grow: 1; flex-shrink: 1; flex-basis: auto
- flex: none 等价于 flex-grow: 0; flex-shrink: 0; flex-basis: auto
使用示例
基本水平居中
.container { display: flex; justify-content: center; align-items: center; height: 200px; }
等分布局
.container { display: flex; } .item { flex: 1; }
全局换行与间距
.container { display: flex; flex-wrap: wrap; gap: 10px; / 项目之间的间距,现代浏览器支持 / } .item { flex: 1 1 200px; / 可以放大,可以缩小,基础大小 200px / }
兼容性
Flexbox 支持所有现代浏览器,包括 IE11(部分属性需加前缀或存在缺陷),对于旧版浏览器,建议使用 Autoprefixer 或降级方案。

相关问题与解答
问题 1:flex: 1 和 flex: auto 有什么区别?
解答:
flex: 1 等价于 flex-grow: 1; flex-shrink: 1; flex-basis: 0%,即项目会平均分配剩余空间,且初始基础大小为 0。
flex: auto 等价于 flex-grow: 1; flex-shrink: 1; flex-basis: auto,即项目会先根据自身内容占据空间,然后分配剩余空间。
当项目内容长度不同时,flex: auto 会使项目保持内容宽度,而 flex: 1 会强制所有项目宽度相等(忽略内容宽度)。

问题 2:如何让 Flex 项目在容器中垂直居中,同时保持项目本身的宽度?
解答:
设置容器 display: flex; align-items: center; 即可让项目在交叉轴(默认垂直方向)居中,如果项目宽度需要保持固定,可以设置 flex-basis 或直接给项目设置 width。
.container { display: flex; align-items: center; height: 300px; } .item { width: 200px; / 固定宽度 / }
这样项目会在垂直方向居中,同时宽度保持 200px。