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

创建可嵌套且保持居中同时不丢失背景的CSS Grid

嘿,我来帮你把这个问题掰扯清楚~

你遇到的核心点其实是网格子元素(grid item)的默认行为和你想要的「背景铺满单元格+内容居中」双重需求之间的匹配问题,咱们一步步拆解:

为什么不加display: grid就达不到效果?

默认情况下,网格容器的子元素(也就是你的那些带编号的item)是普通的块级元素,它有两个关键特性:

  1. 尺寸由内部内容撑开,不会自动铺满它所在的网格单元格
  2. 背景色只会覆盖它自身的「内容+内边距」区域

这时候哪怕你给子元素加了justify-self: center和align-self: center,也只是把这个“内容大小的块”放在了网格单元格的中心位置而已——背景自然只能跟着这个小方块走,没法覆盖整个单元格区域。

加了display: grid之后为什么就生效了?

当你给子元素加上display: grid,它同时拥有了两个身份:

  1. 作为网格子元素:它会继承网格容器的默认对齐规则——justify-self和align-self的默认值是stretch,也就是说这个子元素会自动拉伸,完全填满它所在的网格单元格(不用手动设宽高100%)
  2. 作为网格容器:你可以用place-items: center(或者justify-items: center+align-items: center)让它内部的内容在自己的区域里水平垂直居中

这样一来,背景色跟着拉伸后的子元素铺满整个单元格,内容又在子元素里居中,刚好满足你的两个需求~

给你个直观的代码对比

反面示例(不加display: grid)

.grid-container {
  display: grid;
  grid-template-areas: "item1 item2";
  gap: 10px;
  width: 400px;
  height: 200px;
}

.item1 {
  grid-area: item1;
  background: #ffcccc;
  justify-self: center;
  align-self: center;
}

这时候.item1的背景只会包裹内容,单元格剩下的区域是空的。

正确示例(加display: grid)

.grid-container {
  display: grid;
  grid-template-areas: "item1 item2";
  gap: 10px;
  width: 400px;
  height: 200px;
}

.item1 {
  grid-area: item1;
  background: #ffcccc;
  display: grid;
  place-items: center;
}

这里.item1自动铺满单元格,内容居中,背景全覆盖。

额外补充:还有另一种实现思路

其实不用display: grid也能实现,就是手动让子元素铺满单元格,再用flex居中:

.item1 {
  grid-area: item1;
  background: #ffcccc;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

不过用grid的方式更简洁,因为省去了手动设置宽高的步骤~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:36:05