CSS Grid 布局完全指南

CSS Grid 是目前最强大的 CSS 布局系统。它让复杂的二维布局变得简单直观。

基础概念

容器与项目

/* 容器 */
.container {
  display: grid;
}

/* 子元素自动成为 grid 项目 */

定义列和行

.container {
  display: grid;
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: auto 1fr auto;
}

gap 间距

.container {
  gap: 20px;        /* 行列间距相同 */
  column-gap: 30px; /* 列间距 */
  row-gap: 20px;    /* 行间距 */
}

常用布局模式

圣杯布局

.layout {
  display: grid;
  grid-template: 
    "header header header" auto
    "nav    main   aside" 1fr
    "footer footer footer" auto
    / 200px 1fr 200px;
  min-height: 100vh;
}

响应式卡片网格

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

无需媒体查询,自动适应不同屏幕宽度。

居中布局

.center {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

项目定位

.item {
  grid-column: 1 / 3;  /* 跨两列 */
  grid-row: 2 / 4;     /* 跨两行 */
}

/* 或使用 span */
.item {
  grid-column: span 2;
  grid-row: span 2;
}

对齐

.container {
  /* 项目对齐 */
  justify-items: center;  /* 水平 */
  align-items: center;    /* 垂直 */
  
  /* 内容对齐 */
  justify-content: center;
  align-content: center;
}

/* 单个项目 */
.item {
  justify-self: end;
  align-self: start;
}

总结

CSS Grid 让布局变得声明式、直观、强大。掌握它能大幅提升 CSS 开发效率。

Grid