Flexbox 弹性布局
display:flex、主轴/交叉轴、justify-content/align-items/flex 属性
Flexbox 弹性布局
Flexbox 是现代 CSS 布局的基石——一行代码就能实现复杂的对齐和分布。
学完本章你将: 掌握 display:flex、主轴/交叉轴、justify-content/align-items/flex。
基本概念
css
.container {
display: flex;
/* 自动创建:主轴(默认水平)、交叉轴(垂直) */
}
容器属性
css
.container {
display: flex;
/* 排列方向 */
flex-direction: row; /* row/column/row-reverse/column-reverse */
/* 主轴对齐 */
justify-content: space-between; /* flex-start/center/flex-end/space-between/space-around/space-evenly */
/* 交叉轴对齐 */
align-items: center; /* stretch/flex-start/center/flex-end/baseline */
/* 换行 */
flex-wrap: wrap; /* nowrap/wrap/wrap-reverse */
/* 多行时行间对齐 */
align-content: space-between; /* 类似 justify-content,但作用于交叉轴 */
}
子项属性
css
.item {
flex: 1; /* flex-grow flex-shrink flex-basis 简写——等分剩余空间 */
/* flex: 1 1 0% */
flex-grow: 1; /* 放大比例 */
flex-shrink: 0; /* 不缩小 */
flex-basis: 200px; /* 初始尺寸 */
align-self: center; /* 单独覆盖 align-items */
order: 1; /* 排序(默认 0,数值越小越靠前) */
}
常见布局
css
/* 水平居中 */
.h-center { display: flex; justify-content: center; }
/* 垂直居中 */
.v-center { display: flex; align-items: center; height: 300px; }
/* 完美居中 */
.center { display: flex; justify-content: center; align-items: center; }
/* 两端对齐 */
.space-between { display: flex; justify-content: space-between; }
/* 三列等分 */
.cols { display: flex; }
.cols > * { flex: 1; }