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

display:grid中grid-gap问题:间隙非白色、文本垂直居中如何解决

解决网格间隙颜色与文本垂直居中问题

一、网格间隙显示为#96ceb4而非白色的修复

问题根源

你的CSS选择器逻辑错误——.container div:nth-child(1)这类选择器把背景色直接应用在了网格容器(.one和.two)上,而网格间隙的颜色默认继承容器的背景色,导致间隙跟着容器变成了#96ceb4。

修复步骤

  1. 修正选择器,仅将背景色应用到网格容器内部的子元素(即单个网格项),比如用.container .one div:nth-child(n)和.container .two div:nth-child(n)替代原有选择器。
  2. 给网格容器(.one和.two)显式设置background: #fff,确保间隙颜色固定为白色,避免继承父元素样式。

二、文本垂直居中的实现

问题根源

text-align: center仅控制水平方向对齐,无法处理垂直方向的居中需求。

两种可行实现方法

方法1:给单个网格项添加Flex布局

在网格项的基础样式中加入以下代码,让文本自动水平垂直居中:

display: flex;
align-items: center;
justify-content: center;

方法2:给网格容器设置全局对齐

直接在.one和.two的样式中添加Grid原生属性,让容器内所有网格项的内容自动居中:

place-items: center;

注:两种方法二选一即可,无需重复设置。


修正后的完整代码

body {
  padding: 50px;
}

/* 网格项基础样式 */
.container > div > div {
  color: #fff;
  font-size: 1.5rem;
  /* 方法1:Flex实现垂直+水平居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 网格项背景色设置 */
.container .one div:nth-child(1),
.container .two div:nth-child(1) {
  background: #96ceb4;
}

.container .one div:nth-child(2),
.container .two div:nth-child(2) {
  background: #ff6f69;
}

.container .one div:nth-child(3),
.container .two div:nth-child(3) {
  background: #88d8b0;
}

.container .one div:nth-child(4),
.container .two div:nth-child(4) {
  background: #ffcc5c;
}

.container .one div:nth-child(5),
.container .two div:nth-child(5) {
  background: #96ceb4;
}

.container .one div:nth-child(6),
.container .two div:nth-child(6) {
  background: #ff6f69;
}

.one {
  display: grid;
  grid-template-columns: 100px auto 100px;
  grid-template-rows: 60px 100px;
  grid-gap: 10px;
  background: #fff;
  /* 方法2:Grid全局居中,启用时注释掉上面的Flex代码 */
  /* place-items: center; */
}

.two {
  display: grid;
  grid-template-columns: 100px auto;
  grid-template-rows: 60px 100px;
  grid-gap: 10px;
  background: #fff;
  /* place-items: center; */
}
<div class="container">
  <div class="one">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
  </div>

  <br>

  <div class="two">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:31:19