1. Flexbox 基本概念
Flexbox(弹性盒子布局)是 CSS3 中一种新的布局模式,专门为流式布局设计,可以轻松实现各种灵活的页面布局。
核心特点:
-
一维布局:一次只能处理一个维度(行或列)的布局
-
弹性伸缩:容器内项目可以自动伸缩以适应可用空间
-
对齐简便:提供了强大的对齐和空间分配能力
-
方向可控:可以轻松改变项目的排列方向
2. 基本用法
.container {
display: flex; /* 或 inline-flex */
}
3. Flex 容器属性
3.1 flex-direction - 主轴方向
.container {
flex-direction: row | row-reverse | column | column-reverse;
}
-
row
(默认):从左到右水平排列 -
row-reverse
:从右到左水平排列 -
column
:从上到下垂直排列 -
column-reverse
:从下到上垂直排列
3.2 flex-wrap - 换行方式
.container {
flex-wrap: nowrap | wrap | wrap-reverse;
}
-
nowrap
(默认):不换行 -
wrap
:换行,第一行在上方 -
wrap-reverse
:换行,第一行在下方
3.3 flex-flow - 简写属性
.container {
flex-flow: <flex-direction> <flex-wrap>;
}
示例:
.container {
flex-flow: row wrap;
}
3.4 justify-content - 主轴对齐
.container {
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
}
-
flex-start
(默认):左对齐 -
flex-end
:右对齐 -
center
:居中对齐 -
space-between
:两端对齐,项目间隔相等 -
space-around
:每个项目两侧间隔相等 -
space-evenly
:所有间隔完全相等
3.5 align-items - 交叉轴对齐(单行)
.container {
align-items: stretch | flex-start | flex-end | center | baseline;
}
-
stretch
(默认):拉伸填满容器高度 -
flex-start
:顶部对齐 -
flex-end
:底部对齐 -
center
:垂直居中对齐 -
baseline
:项目的第一行文字的基线对齐
3.6 align-content - 交叉轴对齐(多行)
.container {
align-content: stretch | flex-start | flex-end | center | space-between | space-around;
}
(属性值与 justify-content 类似)
4. Flex 项目属性
4.1 order - 排列顺序
.item {
order: <integer>; /* 默认 0 */
}
数值越小,排列越靠前
4.2 flex-grow - 放大比例
.item {
flex-grow: <number>; /* 默认 0 */
}
定义项目的放大比例,默认为0(不放大)
4.3 flex-shrink - 缩小比例
.item {
flex-shrink: <number>; /* 默认 1 */
}
定义项目的缩小比例,默认为1(空间不足时缩小)
4.4 flex-basis - 初始大小
.item {
flex-basis: <length> | auto; /* 默认 auto */
}
定义项目在分配多余空间之前的初始大小
4.5 flex - 简写属性
.item {
flex: <flex-grow> <flex-shrink> <flex-basis>;
}
常用简写:
.item {
flex: 1; /* 等同于 flex: 1 1 0 */
flex: auto; /* 等同于 flex: 1 1 auto */
flex: none; /* 等同于 flex: 0 0 auto */
}
4.6 align-self - 单独对齐方式
.item {
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
允许单个项目有与其他项目不一样的对齐方式
5. 实用布局示例
5.1 水平居中
.container {
display: flex;
justify-content: center;
}
5.2 垂直居中
.container {
display: flex;
align-items: center;
}
5.3 完美居中
.container {
display: flex;
justify-content: center;
align-items: center;
}
5.4 等宽列布局
.container {
display: flex;
}
.item {
flex: 1;
}
5.5 圣杯布局
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header, .footer {
flex: 0 0 auto;
}
.content {
flex: 1;
display: flex;
}
.main {
flex: 1;
}
.sidebar {
flex: 0 0 200px;
}
6. 注意事项
-
浏览器兼容性:现代浏览器都支持 Flexbox,但某些旧版本可能需要前缀
-
嵌套限制:过度嵌套 Flex 容器可能影响性能
-
最小尺寸:Flex 项目默认不会缩小到小于其内容的最小尺寸
-
流式布局:Flexbox 特别适合响应式设计,可以轻松适应不同屏幕尺寸
-
与 Grid 比较:简单一维布局用 Flexbox,复杂二维布局用 CSS Grid
7. 最佳实践
-
优先使用简写属性
flex
而不是单独设置flex-grow
、flex-shrink
和flex-basis
-
使用
flex-wrap: wrap
实现响应式流式布局 -
合理使用
min-width
/max-width
控制 Flex 项目的尺寸限制 -
结合媒体查询创建不同断点的 Flex 布局
-
使用
gap
属性(现代浏览器支持)替代 margin 设置项目间距
Flexbox 提供了强大的流式布局能力,通过合理使用各种属性,可以轻松实现各种复杂的布局需求,同时保持代码的简洁和可维护性。