主题
概念卡片:CSS Flex 布局
一句话机制:Flex 是一维布局模型——容器设
display: flex后,用justify-content控制主轴对齐、align-items控制交叉轴对齐,子项用flex按比例分配剩余空间。开启 flex 的元素叫 flex container,其直接子元素叫 flex item。
关键概念:主轴与交叉轴
主轴 main axis ← flex-direction 决定(row 默认横向 / column 纵向)
交叉轴 cross axis ← 垂直于主轴justify-content 管主轴、align-items 管交叉轴,两者不可互换。
容器 6 属性
css
.box {
display: flex; /* 或 inline-flex */
flex-direction: row | column; /* 主轴方向 */
flex-wrap: nowrap | wrap; /* 换行 */
justify-content: flex-start | center | space-between | space-around | space-evenly;
align-items: flex-start | center | stretch | baseline;
align-content: /* 多行时交叉轴对齐 */
}justify-content 三个易混值:
| 值 | 效果 |
|---|---|
space-between | 两端对齐,item 之间间隔相等 |
space-around | 每个 item 两侧间隔相等(item 之间是边框的 2 倍) |
space-evenly | 所有间隔(含边框)完全相等 |
子项 6 属性
css
.item {
order: 0; /* 排列顺序,越小越靠前 */
align-self: auto; /* 单项目覆盖 align-items */
flex-grow: 0; /* 放大比例(默认 0 不放大) */
flex-shrink: 1; /* 缩小比例(默认 1 可缩小) */
flex-basis: auto; /* 主轴基准大小 */
flex: 0 1 auto; /* 上面三者的简写 */
}flex 简写与快捷值
| 写法 | 等价 |
|---|---|
flex: 1 | 1 1 0%(均分剩余空间) |
flex: auto | 1 1 auto |
flex: none | 0 0 auto |
| 默认 | 0 1 auto |
flex-grow计算:剩余空间按flex-grow比例分配;若所有flex-grow总和 ≤ 1,则只分走剩余空间 × flex-grow。
隐藏元素的三种方式
| 方式 | 是否占位 | 是否可交互 |
|---|---|---|
display: none | 不占位 | 否 |
visibility: hidden | 占位 | 否 |
opacity: 0 | 占位 | 是 |
不变量(必须成立的约束)
- 主轴方向由
flex-direction决定,justify-content/align-items一个管主轴、一个管交叉轴,不可互换。 flex: 1是flex-grow:1; flex-shrink:1; flex-basis:0的简写,用于均分剩余空间。display:none移除元素(不占位),visibility:hidden只隐藏(仍占位)。- 建议用
flex简写而非单独写三个属性,浏览器会推算相关值。
踩坑案例
- 现象:想垂直居中,写了
justify-content: center却只在水平方向居中。 原因:flex-direction默认 row,主轴是横向,justify-content管横向。解决:垂直居中用align-items: center。
常见误解
- 搞混主轴/交叉轴 → 换
flex-direction后justify-content和align-items效果「对调」,先确认主轴方向。 - 以为
display:none和visibility:hidden一样 → 前者不占位、后者占位,影响布局。
关联
- 总览:React技术栈总览
- 源:
B40-资源/语雀-Java开发/前端技术/✅CSS(Flex 布局 / 隐藏元素 2 篇)