Appearance
CSS Flexbox 布局
Flexbox(弹性盒子)是一种用于一维布局的 CSS 布局模式。
概述
Flexbox 适用于在容器中分布空间和对齐内容,特别适合组件和小规模布局。
容器属性
display
定义弹性容器:
css
.flex-container {
display: flex; /* 主轴为水平方向 */
display: inline-flex; /* 行内弹性容器 */
}
flex-direction
定义主轴方向:
css
.container {
flex-direction: row; /* 默认值,水平方向,从左到右 */
flex-direction: row-reverse; /* 水平方向,从右到左 */
flex-direction: column; /* 垂直方向,从上到下 */
flex-direction: column-reverse; /* 垂直方向,从下到上 */
}
flex-wrap
定义是否换行:
css
.container {
flex-wrap: nowrap; /* 默认值,不换行 */
flex-wrap: wrap; /* 换行 */
flex-wrap: wrap-reverse; /* 反向换行 */
}
flex-flow
flex-direction 和 flex-wrap 的简写:
css
.container {
flex-flow: row wrap; /* 方向和换行 */
}
justify-content
定义主轴上的对齐方式:
css
.container {
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
定义交叉轴上的对齐方式:
css
.container {
align-items: stretch; /* 默认值,拉伸以填满容器 */
align-items: flex-start; /* 交叉轴起点对齐 */
align-items: flex-end; /* 交叉轴终点对齐 */
align-items: center; /* 交叉轴中点对齐 */
align-items: baseline; /* 项目第一行文字基线对齐 */
}
align-content
定义多根轴线的对齐方式(仅在多行时有效):
css
.container {
align-content: flex-start; /* 与交叉轴起点对齐 */
align-content: flex-end; /* 与交叉轴终点对齐 */
align-content: center; /* 与交叉轴中点对齐 */
align-content: space-between; /* 与交叉轴两端对齐 */
align-content: space-around; /* 每根轴线两侧间隔相等 */
align-content: stretch; /* 默认值,轴线占满整个交叉轴 */
}
项目属性
order
定义项目的排列顺序:
css
.item {
order: 0; /* 默认值 */
order: -1; /* 排在前面 */
order: 1; /* 排在后面 */
}
flex-grow
定义项目的放大比例:
css
.item {
flex-grow: 0; /* 默认值,不放大 */
flex-grow: 1; /* 按比例分配剩余空间 */
}
flex-shrink
定义项目的缩小比例:
css
.item {
flex-shrink: 1; /* 默认值,等比例缩小 */
flex-shrink: 0; /* 不缩小 */
}
flex-basis
定义项目在分配多余空间前的默认大小:
css
.item {
flex-basis: auto; /* 默认值 */
flex-basis: 100px; /* 固定大小 */
}
flex
flex-grow、flex-shrink 和 flex-basis 的简写:
css
.item {
flex: 0 1 auto; /* 默认值 */
flex: 1; /* 等价于 flex: 1 1 0% */
flex: 0 0 auto; /* 不伸缩 */
}
align-self
允许单个项目有与其他项目不同的对齐方式:
css
.item {
align-self: auto; /* 默认值,继承父元素的 align-items */
align-self: flex-start; /* 与其他项目不同的对齐方式 */
align-self: flex-end;
align-self: center;
align-self: baseline;
align-self: stretch;
}
实用示例
水平垂直居中
css
.center-container {
display: flex;
justify-content: center;
align-items: center;
}
底部对齐
css
.bottom-container {
display: flex;
flex-direction: column;
justify-content: flex-end;
height: 100vh;
}
等高列
css
.equal-height {
display: flex;
}
.equal-height > div {
flex: 1; /* 等比例分配宽度 */
}
浏览器兼容性
现代浏览器普遍支持 Flexbox,但旧版本浏览器可能需要前缀:
css
.flex-container {
display: -webkit-box; /* 旧版本 */
display: -webkit-flex; /* Safari 6.1+ */
display: -ms-flexbox; /* IE 10 */
display: flex; /* 标准语法 */
}
最佳实践
- 使用 Flexbox 处理一维布局(行或列)
- 理解主轴和交叉轴的概念
- 合理使用 flex 简写属性
- 考虑老版本浏览器的兼容性