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

CSS Grid中justify-content不生效的原因及解决方法

问题原因与解决办法

原因

justify-content 在 CSS Grid 中生效的前提是:网格轨道的总宽度小于网格容器的可用宽度,它的作用是控制轨道在容器内的水平分布。

你的代码中 .grid-2-cols 设置了 grid-template-columns: 1fr 1fr,1fr 会平分容器的可用宽度,最终两个轨道的总宽度等于容器宽度,没有剩余空间,所以 justify-content: center 无法发挥作用。而 align-items 生效是因为网格项的高度不一致,容器在垂直方向有剩余空间可以让它控制对齐。

解决办法

根据你的需求选择对应方案:

方案1:让网格轨道整体在容器内水平居中

修改 grid-template-columns,让轨道总宽度小于容器宽度,比如:

.grid-2-cols {
  grid-template-columns: repeat(2, auto); /* 轨道宽度由内容决定 */
  /* 或者指定固定宽度,比如:grid-template-columns: 30rem 30rem; */
}

此时轨道总宽小于容器,justify-content: center 会让轨道整体居中。

方案2:让网格项内部的内容水平居中

如果你的需求是让每个网格项(.step-text-box 和 .step-img-box)里的内容水平居中,应该用 justify-items 代替 justify-content:

.grid-center {
  align-items: center;
  justify-items: center; /* 控制网格项内容的水平对齐 */
}

如果需要更精细控制单个网格项的内容对齐,也可以直接给网格项设置 justify-self: center:

.step-text-box, .step-img-box {
  justify-self: center;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:05:20