
CSS Grid 中 grid-row 的值应基于行线(row lines)而非行数,错误的行线索引会导致网格项高度错乱;正确设置需将 6 行内容对应 7 条行线(1–7),并据此调整各 .item 的 grid-row 范围。
css grid 中 `grid-row` 的值应基于行线(row lines)而非行数,错误的行线索引会导致网格项高度错乱;正确设置需将 6 行内容对应 7 条行线(1–7),并据此调整各 `.item` 的 `grid-row` 范围。
在使用 CSS Grid 布局时,一个常见却容易被忽视的理解误区是:grid-row: a/b 并非指定“跨越第 a 行到第 b 行”,而是指从第 a 条行线(row line)延伸到第 b 条行线。Grid 容器默认按 grid-template-rows 划分行轨道(tracks),而每条轨道由上下两条行线界定。即使未显式定义 grid-template-rows,浏览器仍会根据内容自动创建隐式行轨道,并生成对应的行线编号。
在你的代码中,.box 容器虽未声明 grid-template-rows,但通过 grid-row 显式跨行(如 1/6),实质上是在引用隐式生成的行线。由于你共有 6 个网格项、且布局意图是三列多行结构(第一列 1 项占满,第二列 2 项分上下,第三列 3 项等分),逻辑上整个网格应划分为 6 个等高行轨道 → 对应 7 条水平行线(line 1 至 line 7)。
而原代码中:
- .item:first-child { grid-row: 1/6; } —— 实际只跨越前 5 条轨道(line 1 → line 6),缺失最后一行;
- .item:nth-child(2) { grid-row: 1/3; } 和 .item:nth-child(3) { grid-row: 3/6; } —— 第二项占 2 行,第三项占 3 行,高度自然不等;
- 同理,第四至第六项的 1/2、2/4、4/6 组合导致第三列总高度仅覆盖 line 1 → line 6(5 行),与第一列(应为 6 行)和第二列(1/4 + 4/7 = 6 行)失配。
✅ 正确做法是统一以 7 条行线为基准(1–7) 进行划分:
立即学习“前端免费学习笔记(深入)”;
.box {
width: 750px;
height: 360px;
display: grid;
grid-template-columns: 44% 32% 24%;
/* 可选:显式定义等高行,增强可控性 */
grid-template-rows: repeat(6, 1fr); /* 6 个等高行轨道 */
}
.item {
background: #b3b3b3;
border: 1px solid #000;
color: #fff;
padding: 15px;
}
/* 第一列:单一项,占满全部 6 行 → line 1 到 line 7 */
.item:first-child {
grid-row: 1 / 7;
}
/* 第二列:两项,均分 6 行 → 各占 3 行 */
.item:nth-child(2) {
background: #898995;
grid-row: 1 / 4; /* line 1 → line 4 = 3 行 */
}
.item:nth-child(3) {
background: #898995;
grid-row: 4 / 7; /* line 4 → line 7 = 3 行 */
}
/* 第三列:三项,均分 6 行 → 各占 2 行 */
.item:nth-child(4) {
background: #7a7a7a;
grid-row: 1 / 3; /* line 1 → line 3 = 2 行 */
}
.item:nth-child(5) {
background: #7a7a7a;
grid-row: 3 / 5; /* line 3 → line 5 = 2 行 */
}
.item:nth-child(6) {
background: #7a7a7a;
grid-row: 5 / 7; /* line 5 → line 7 = 2 行 */
}? 关键提示:
- 行线编号始终从 1 开始,n 行轨道 ⇒ n+1 条行线;
- 使用 grid-template-rows: repeat(6, 1fr) 可显式约束行高比例,避免隐式轨道因内容差异导致高度波动;
- 若需响应式或动态内容,建议结合 minmax() 或 auto-fit 等函数增强鲁棒性;
- Chrome DevTools 的 Grid Inspector(在 Elements 面板勾选 “Show line numbers”)可直观验证行线分布。
修正后,所有列的总高度严格对齐,各网格项在垂直方向均匀分布,视觉一致性得以保障。


















