You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grid布局中网格项高度不均问题求助

Grid网格项高度不均问题解决

问题说明

使用Grid布局制作网格时,出现以下问题:

  • 第2、3个网格项高度不一致
  • 第4、5、6个网格项在对应列中高度不均

原始代码

HTML代码

<div class="box">
  <div class="item">Плитка 1</div>
  <div class="item">Плитка 2</div>
  <div class="item">Плитка 3</div>
  <div class="item">Плитка 4</div>
  <div class="item">Плитка 5</div>
  <div class="item">Плитка 6</div>
</div>

CSS代码

.box {
  width: 750px;
  height: 360px;
  display: grid;
  grid-template-columns: 44% 32% 24%;
}

.item {
  background: #b3b3b3;
  border: 1px solid #000;
  color: #fff;
  padding: 15px;
}

.item:first-child {
  grid-row: 1/6;
}

.item:nth-child(2){
  background: #898995;
  grid-row: 1/3;
}
.item:nth-child(3) {
  background: #898995;
  grid-row: 3/6;
}

.item:nth-child(4){
  grid-row: 1/2;
  background: #7a7a7a;
}
.item:nth-child(5){
  grid-row: 2/4;
  background: #7a7a7a;
}
.item:nth-child(6) {
  grid-row: 4/6;
  background: #7a7a7a;
}

问题原因

核心问题是未显式定义网格行高:

  • 仅设置了grid-template-columns划分列,但未指定grid-template-rows,Grid会自动计算行高。
  • 不同列的网格项跨行数不同,自动计算的行高会因布局平衡逻辑、元素内边距/边框等因素出现差异,导致跨多行的网格项高度不均。
  • 比如第2个网格项跨1-3行、第3个跨3-6行,自动分配的行高不统一,最终两者高度不等;第4-6个网格项同理。

解决方案

通过显式设置均等行高,并修正盒模型计算方式来解决:

修改后的CSS代码

.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;
  box-sizing: border-box; /* 让内边距和边框包含在元素尺寸内 */
}

/* 以下选择器保持不变 */
.item:first-child {
  grid-row: 1/6;
}

.item:nth-child(2){
  background: #898995;
  grid-row: 1/3;
}
.item:nth-child(3) {
  background: #898995;
  grid-row: 3/6;
}

.item:nth-child(4){
  grid-row: 1/2;
  background: #7a7a7a;
}
.item:nth-child(5){
  grid-row: 2/4;
  background: #7a7a7a;
}
.item:nth-child(6) {
  grid-row: 4/6;
  background: #7a7a7a;
}

关键修改说明

  1. grid-template-rows: repeat(6, 1fr):让容器的6行高度完全均等,确保跨多行的网格项高度比例准确。
  2. box-sizing: border-box:避免内边距和边框额外撑开元素高度,保证行高计算不受影响。

内容的提问来源于stack exchange,提问作者Max xaM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:33:31