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

如何让CSS Grid中的div均匀占空间?6个div网格布局右侧占比异常排查

代码存在的问题

  • grid-template-rows、grid-template-columns的属性值错误添加了引号,仅grid-template-areas的区域定义需要用引号包裹,这两个尺寸属性加引号会导致浏览器无法正常解析行列尺寸规则,是右侧列占比异常的核心原因
  • grid-template-rows定义了3个行轨道值,但是你的布局实际只有2行(grid-template-areas仅定义了2行区域),多余的行规则会产生无效空白行,干扰布局效果

修正方案

把多余的引号删除,同时根据实际布局的行列数配置轨道尺寸即可,用相同数值的fr单位即可实现所有盒子均匀分配空间。

修正后的完整CSS代码如下:

.second-box{
  display: grid;
  /* 配置2行,每行高度等分 */
  grid-template-rows: 1fr 1fr;
  /* 配置3列,每列宽度等分 */
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-areas: 
  "box1 box2 box3"
  "box4 box5 box6";
  margin: 50px;
  /* 如需固定网格容器高度,可自行添加height属性,例如 height: 500px; */
}

.box1{
  background-color: darkolivegreen;
  grid-area: box1;
}

.box2{
  background-color: rgba(108, 148, 39, 0.267);
  grid-area: box2;
}

.box3{
  background-color: darkgoldenrod ;
  grid-area: box3;
}

.box4{
  background-color: fuchsia;
  grid-area: box4;
}

.box5{
  background-color: darkcyan;
  grid-area: box5;
}

.box6{
  background-color:darkgrey;
  grid-area: box6;
}

如果希望网格盒子无内容时也能展示默认高度,可以给所有盒子统一添加min-height属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:30:00