CSS Flexbox 完全指南:一文搞懂弹性布局
Flexbox 是 CSS3 中的弹性布局模型,可以轻松实现各种复杂的布局需求。
基本概念
容器属性
.container {
display: flex;
flex-direction: row; /* 主轴方向 */
justify-content: center; /* 主轴对齐 */
align-items: center; /* 交叉轴对齐 */
flex-wrap: wrap; /* 是否换行 */
gap: 10px; /* 间距 */
}
项目属性
.item {
flex-grow: 1; /* 放大比例 */
flex-shrink: 0; /* 缩小比例 */
flex-basis: auto; /* 初始大小 */
order: 0; /* 排列顺序 */
align-self: auto; /* 单独对齐 */
}
主轴方向
/* 水平排列(默认) */
flex-direction: row;
/* 水平反向排列 */
flex-direction: row-reverse;
/* 垂直排列 */
flex-direction: column;
/* 垂直反向排列 */
flex-direction: column-reverse;
对齐方式
主轴对齐(justify-content)
/* 起点对齐 */
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)
/* 起点对齐 */
align-items: flex-start;
/* 终点对齐 */
align-items: flex-end;
/* 居中对齐 */
align-items: center;
/* 拉伸对齐 */
align-items: stretch;
/* 基线对齐 */
align-items: baseline;
常见布局示例
水平垂直居中
.center {
display: flex;
justify-content: center;
align-items: center;
}
等分布局
.equal-width {
display: flex;
}
.equal-width > * {
flex: 1;
}
固定 + 自适应
.layout {
display: flex;
}
.sidebar {
width: 200px;
flex-shrink: 0;
}
.content {
flex: 1;
}
底部固定
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.content {
flex: 1;
}
.footer {
/* 自然在底部 */
}
Flex 缩写
/* flex: flex-grow flex-shrink flex-basis */
flex: 1; /* flex: 1 1 0% */
flex: auto; /* flex: 1 1 auto */
flex: none; /* flex: 0 0 auto */
flex: 200px; /* flex: 1 1 200px */
浏览器支持
Flexbox 在所有现代浏览器中都得到支持:
- Chrome 29+
- Firefox 28+
- Safari 9+
- Edge 12+
最佳实践
- 优先使用 Flexbox:比 float 更现代、更强大
- 避免固定高度:让内容决定高度
- 使用 gap:比 margin 更简洁
- 结合 Grid:复杂布局使用 Grid
总结
Flexbox 是现代 CSS 布局的基础。掌握 Flexbox,可以轻松实现各种复杂的布局需求。