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

CSS grid-template-areas布局异常,如何正确还原目标布局?

解决grid-template-areas布局不显示的问题

问题描述

尝试使用grid-template-areas重建布局,但该属性无法正常工作,代码逻辑看似无误却找不到问题,需要还原如图所示的目标布局:

目标布局

用户提供的代码如下:

HTML代码

<div class="grid-container">
  <div class="a"></div>
  <div class="b"></div>
  <div class="c"></div>
  <div class="d"></div>
  <div class="e"></div>
  <div class="f"></div>
</div>

CSS代码

.a {
  background: red;
  grid-area: a;
}

.b {
  background: green;
  grid-area: b;
}

.c {
  background: aqua;
  grid-area: c;
}

.d {
  background: darkblue;
  grid-area: d;
}

.e {
  background: purple;
  grid-area: e;
}

.f {
  background: orange;
  grid-area: f;
}

.grid-container {
  display: grid;
  margin: auto;
  grid-gap: 8px;
  grid-template-areas: "a a a a" "b c c c" "b c c c" "b c c c" "b c c c" ". . d d" "e e e e" "e e e e" "e e e e" "f f f f";
}

问题原因

你的grid-template-areas区域定义逻辑是正确的,但缺少了列宽和行高的设置:

  • Grid容器默认行高为auto,而你的网格项没有内容,导致高度塌陷为0,无法显示背景色;
  • 未定义列宽,容器无法明确网格的列分布规则。

修正后的代码

给Grid容器添加列宽、行高的定义,同时使用标准的gap属性替代grid-gap:

.a {
  background: red;
  grid-area: a;
}

.b {
  background: green;
  grid-area: b;
}

.c {
  background: aqua;
  grid-area: c;
}

.d {
  background: darkblue;
  grid-area: d;
}

.e {
  background: purple;
  grid-area: e;
}

.f {
  background: orange;
  grid-area: f;
}

.grid-container {
  display: grid;
  margin: auto;
  gap: 8px;
  width: 80%; /* 给容器设置宽度,适配展示需求 */
  /* 定义4列,每列等宽分配容器宽度 */
  grid-template-columns: repeat(4, 1fr);
  /* 对应grid-template-areas的10行,设置每行高度 */
  grid-template-rows: 60px repeat(4, 80px) 60px repeat(3, 80px) 60px;
  grid-template-areas: 
    "a a a a" 
    "b c c c" 
    "b c c c" 
    "b c c c" 
    "b c c c" 
    ". . d d" 
    "e e e e" 
    "e e e e" 
    "e e e e" 
    "f f f f";
}

关键说明

  • grid-template-columns: repeat(4, 1fr):和grid-template-areas里的4列结构对应,每列占容器宽度的1/4;
  • grid-template-rows:根据目标布局的视觉比例,给每行设置具体高度,让网格项有足够空间显示背景色;
  • gap:是grid-gap的标准替代写法,作用一致,语法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:01:10