Flexbox 弹性布局
约 643 字大约 2 分钟
布欧-Lewyon
2026-05-16
Flexbox 是一维布局模型——在一个方向(行或列)上灵活分配空间。
基本概念
容器属性
.flex-container {
display: flex; /* 块级弹性容器 */
/* 或 display: inline-flex; 内联弹性容器 */
flex-direction: row; /* 默认:水平方向 */
flex-direction: column; /* 垂直方向 */
flex-direction: row-reverse; /* 水平反转 */
flex-direction: column-reverse; /* 垂直反转 */
flex-wrap: nowrap; /* 默认:不换行 */
flex-wrap: wrap; /* 换行 */
/* 主轴对齐 */
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: stretch; /* 默认:拉伸填满 */
align-items: flex-start; /* 起始对齐 */
align-items: flex-end; /* 结束对齐 */
align-items: center; /* 居中 */
align-items: baseline; /* 文字基线对齐 */
/* 多行交叉轴对齐 */
align-content: flex-start; /* 起始对齐 */
align-content: center; /* 居中 */
align-content: space-between;
}项目属性
.flex-item {
/* ⭐ flex 简写:flex-grow flex-shrink flex-basis */
flex: 0 1 auto; /* 默认:不放大,可缩小,基准自动 */
flex: 1; /* flex: 1 1 0% — 平分剩余空间 */
flex: auto; /* flex: 1 1 auto */
flex: none; /* flex: 0 0 auto — 固定大小 */
/* 单独属性 */
flex-grow: 1; /* 放大比例,0=不放大 */
flex-shrink: 1; /* 缩小比例,0=不缩小 */
flex-basis: auto; /* 初始大小 */
order: 0; /* 排序(数值越小越靠前) */
align-self: center; /* 单独覆盖 align-items */
}常用模式
/* 水平居中 + 垂直居中 */
.center {
display: flex;
justify-content: center;
align-items: center;
}
/* 等分列 */
.equal-cols {
display: flex;
}
.equal-cols > * {
flex: 1; /* 每个子项平均分宽度 */
}
/* 右侧固定,左侧自适应 */
.sidebar-layout {
display: flex;
}
.sidebar { flex: 0 0 240px; } /* 固定 240px */
.main { flex: 1; } /* 占剩余空间 */
/* 底部固定 */
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.content { flex: 1; } /* 中间撑满,footer 在底部 */小结
| 属性 | 作用 |
|---|---|
display: flex | 弹性容器 |
flex-direction | 主轴方向 |
justify-content | 主轴对齐 |
align-items | 交叉轴对齐 |
flex: 1 | 等比放大 |
order | 排序 |
align-self | 单独对齐 |
