CSS Grid 布局完全指南
什么是 Grid 布局
CSS Grid Layout 是 CSS 中最强大的布局系统。它将页面划分为行和列组成的网格,可以精确控制元素在网格中的位置和尺寸。与 Flexbox(一维布局)不同,Grid 是二维布局系统。
基本概念
网格容器(Grid Container)
.container {
display: grid;
}
网格项目(Grid Item)
容器的直接子元素自动成为网格项目。
网格线(Grid Line)
构成网格结构的分界线,分为行网格线和列网格线。
网格单元(Grid Cell)
相邻四根网格线围成的最小区域。
网格区域(Grid Area)
由任意数量网格单元组成的矩形区域。
容器属性
grid-template-columns / grid-template-rows
.container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto 300px;
/* 三列:固定200px + 两等份剩余空间 */
/* 两行:自动高度 + 固定300px */
}
repeat 函数
.container {
/* 重复3次,每份1fr */
grid-template-columns: repeat(3, 1fr);
/* 重复模式:200px 1fr 重复3次 */
grid-template-columns: repeat(3, 200px 1fr);
/* auto-fill:自动填充尽可能多的列 */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
gap 属性
.container {
gap: 20px; /* 行和列间距 */
row-gap: 10px; /* 行间距 */
column-gap: 20px; /* 列间距 */
}
grid-template-areas
.container {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
justify-items / align-items
.container {
justify-items: center; /* 水平居中 */
align-items: stretch; /* 垂直拉伸(默认) */
place-items: center; /* 同时设置两者,居中 */
}
justify-content / align-content
.container {
grid-template-columns: 200px 200px;
justify-content: space-between; /* 列之间均匀分布 */
align-content: center; /* 行垂直居中 */
}
项目属性
grid-column / grid-row
.item {
/* 从第1列线到第3列线 */
grid-column: 1 / 3;
/* 从第2行线开始,跨越2行 */
grid-row: 2 / span 2;
/* 简写:列起始/行起始/列结束/行结束 */
grid-area: 1 / 1 / 3 / 3;
}
justify-self / align-self
.item {
justify-self: end; /* 水平右对齐 */
align-self: center; /* 垂直居中 */
place-self: center; /* 同时设置 */
}
实战:响应式博客布局
.blog-layout {
display: grid;
gap: 20px;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
}
/* 平板 */
@media (min-width: 768px) {
.blog-layout {
grid-template-columns: 1fr 300px;
grid-template-areas:
"header header"
"main sidebar"
"footer footer";
}
}
/* 桌面 */
@media (min-width: 1024px) {
.blog-layout {
grid-template-columns: 200px 1fr 300px;
grid-template-areas:
"header header header"
"nav main sidebar"
"footer footer footer";
}
}
自动填充卡片网格
.card-grid {
display: grid;
gap: 20px;
/* 每列最小250px,尽可能多放,自动适配 */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
常见布局模式
圣杯布局
.holy-grail {
display: grid;
grid-template: auto 1fr auto / 200px 1fr 200px;
min-height: 100vh;
}
.holy-grail > :nth-child(1) { grid-column: 1 / -1; } /* header */
.holy-grail > :nth-child(4) { grid-column: 1 / -1; } /* footer */
居中布局
.center {
display: grid;
place-items: center;
min-height: 100vh;
}
总结
CSS Grid 是二维布局的终极方案,适合页面级整体布局。日常开发中 Grid 和 Flexbox 配合使用:Grid 负责页面整体结构,Flexbox 负责组件内部的一维排列。掌握 Grid 能让复杂页面的布局工作变得简单直观。