CSS 布局是前端开发中最核心的技能之一。本文梳理 Flexbox 和 Grid 两大现代布局方案。

Flexbox 弹性布局

适用于一维布局(行或列)。

容器属性

1
2
3
4
5
6
7
.container {
display: flex;
flex-direction: row; /* 主轴方向 */
justify-content: center; /* 主轴对齐 */
align-items: center; /* 交叉轴对齐 */
flex-wrap: wrap; /* 换行 */
}

项目属性

1
2
3
4
.item {
flex: 1; /* 伸缩比例 */
align-self: auto; /* 单独对齐 */
}

Grid 网格布局

适用于二维布局(行+列)。

1
2
3
4
5
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}

响应式网格

1
2
3
.container {
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

总结

  • Flexbox:导航栏、居中、一维排列
  • Grid:整体页面布局、卡片网格
  • 两者可以嵌套使用,互补而非替代