CSS Flexbox布局
Flexbox(弹性盒子)是一维布局模型,轻松实现元素的水平/垂直对齐、等分空间、自适应排列。
基本概念
CSS
┌─────────────────────────────────────┐
│ main axis (主轴) │
│ ────────────────────────────────► │
│ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │flex │ │flex │ │flex │ │flex │ │
│ │item │ │item │ │item │ │item │ │
│ └──────┘ └──────┘ └──────┘ └──────┘ │
│ ▲ │
│ │ cross axis (交叉轴) │
└─────────────────────────────────────┘
容器属性
display 开启 Flexbox
CSS
.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; /* 换行,反转 */
}
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 {
flex-wrap: wrap;
align-content: flex-start;
align-content: center;
align-content: space-between;
}
项目属性
flex-grow 放大比例
CSS
.item {
flex-grow: 0; /* 默认,不放大 */
}
.item-grow {
flex-grow: 1; /* 占据剩余空间 */
}
flex-shrink 缩小比例
CSS
.item {
flex-shrink: 1; /* 默认,可缩小 */
}
.item-no-shrink {
flex-shrink: 0; /* 不缩小 */
}
flex-basis 初始大小
CSS
.item {
flex-basis: auto; /* 默认,按内容 */
flex-basis: 200px; /* 固定初始宽度 */
}
flex 简写(推荐)
CSS
.item {
flex: 0 1 auto; /* 默认值 */
flex: 1; /* flex: 1 1 0% */
flex: auto; /* flex: 1 1 auto */
flex: none; /* flex: 0 0 auto */
}
align-self 单独对齐
CSS
.item {
align-self: center; /* 覆盖容器的align-items */
}
常用布局示例
水平垂直居中
CSS
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
等分空间
CSS
.container {
display: flex;
}
.item {
flex: 1; /* 等分 */
}
左右布局
CSS
.header {
display: flex;
justify-content: space-between;
align-items: center;
}
圣杯布局
text
.layout {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main {
display: flex;
flex: 1;
}
.content { flex: 1; }
.sidebar { flex: 0 0 200px; }
要点总结
- 容器属性:
flex-direction、flex-wrap、justify-content、align-items - 项目属性:
flex-grow、flex-shrink、flex-basis、flex简写 flex: 1等分空间,flex: none固定尺寸- 一维布局用 Flexbox,二维布局用 Grid
📝 发现内容有误?点击此处直接编辑