正在加载...

CSS Grid 容器

Grid 入门把父元素变成了网格。本课停留在容器:定义轨道、设置 gap、在单元格内对齐项目,并在仍有空余空间时排布整个网格。项目跨度与命名区域留给 Grid Items 与 Grid Areas。

grid 容器工具箱

📊 grid 容器一览

属性 日常作用
grid-template-columns 定义列轨道尺寸
grid-template-rows 定义行轨道尺寸
gap 轨道之间的间距
justify-items / align-items 在单元格内对齐每个项目(inline / block 轴)
justify-content / align-content 当网格小于容器时定位整个网格
grid-auto-flow 控制自动放置的排布顺序(row 或 column)

先画轨道。再决定单元格如何对齐内容,最后才处理整个网格周围剩余空间的行为。

模板轨道——列与行

grid-template-columns 与 grid-template-rows 勾勒网格。日常面板可混合 fr、长度与 repeat()。

列与行一起

css
.board {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto 1fr auto;
min-height: 16rem;
}

gap——保持诚实的间距

gap(或 row-gap / column-gap)在轨道之间留空,无需给每个子元素打 margin 补丁。

容器上的 gap

css
.board {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem 1.25rem;
}

justify-items 与 align-items——在单元格内

它们对齐每个项目在其单元格内的位置。justify-items 作用于 inline 轴;align-items 作用于 block 轴。不要与内容排布混淆。

在单元格内居中项目

css
.board {
display: grid;
grid-template-columns: repeat(2, 8rem);
justify-items: center;
align-items: center;
gap: 0.75rem;
}

justify-content 与 align-content——排布网格

当轨道小于容器时,content 属性会滑动或拉开整个网格。适合不该无限拉伸的图标面板。

在空余空间排布网格

css
.board {
display: grid;
grid-template-columns: repeat(3, 6rem);
justify-content: space-between;
align-content: start;
gap: 0.5rem;
min-height: 12rem;
}

平稳的 grid 容器习惯

先模板列与行,再 gap,再单元格内项目对齐,若仍有空余再做 content 排布。自动放置顺序重要时再看 grid-auto-flow。跨度、线号与命名区域留给后续 Grid 课。

命名容器外壳

css
.shell {
display: grid;
grid-template-columns: 2fr 1fr;
grid-template-rows: auto 1fr;
gap: 1.25rem;
justify-items: stretch;
align-items: stretch;
}

自己试试

  1. 做一个三列 1fr、行 auto 1fr auto 的面板。
  2. 加上 gap: 1rem。
  3. 用 justify-items 与 align-items 居中单元格内容。
  4. 用 justify-content: space-between 排布固定轨道面板。
  5. 写下一个留给 Grid Items 或 Grid Areas 的属性。

常见错误

  • 把 justify-items(单元格内)与 justify-content(整个网格)搞混
  • 过早在容器上写项目 span 或区域名
  • 只定义列却奇怪行高随机
  • 把 Flex 的 grow 习惯搬到 grid 容器
  • 把本课当成完整 Areas 模块

小结

  • grid 容器属性定义轨道、间距与对齐
  • grid-template-columns / rows 勾勒网格
  • justify-items / align-items 在单元格内对齐内容
  • justify-content / align-content 在空余空间排布网格
  • 项目跨度与命名区域在后续 Grid 课出现

🧠 测试您的知识

准备开始

测试您的知识

通过这个互动测验挑战自己,看看你对这个主题的理解程度如何

❓
8
问题
🎯
70%
及格要求
♾️
∞
时间
🔄
∞
尝试次数

📝 说明

  • 仔细阅读每个问题
  • 为每个问题选择最佳答案
  • 您可以随时重新参加测验
  • 您的进度将显示在顶部