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

如何居中Grid容器及内部内容?附相关代码片段

解决Grid布局中盒子内容居中的问题

嗨,我明白你的困惑啦!你一开始误以为是外层容器没居中,但实际是每个grades_dashboard_box里的<h1>内容没有居中显示。别担心,只需要给每个盒子添加内部内容的对齐样式就能搞定。

解决方案:给单个盒子添加内部居中样式

你需要修改.grades_dashboard_box的CSS,让它内部的元素水平和垂直都居中。最简单的方式是用Flex布局:

.grades_dashboard_m {}
.three_separation { 
  width: 100%; 
  display: grid; 
  grid-template-columns: 1fr 1fr 1fr; 
  grid-gap: 60px; 
}
.grades_dashboard_box { 
  height: 130px; 
  width: 160px; 
  background-color: #000000; 
  color: #fff; /* 修正了#ffff的写法,正确白色值为#fff或#ffffff */
  /* 添加以下样式实现内部内容居中 */
  display: flex;
  justify-content: center;
  align-items: center;
}

对应的HTML保持不变:

<div class="grades_dashboard_m" id="co_1">
  <div class="three_separation">
    <div class='grades_dashboard_box'>
      <h1>12</h1>
    </div>
    <div class='grades_dashboard_box'>
      <h1>12</h1>
    </div>
    <div class='grades_dashboard_box'>
      <h1>12</h1>
    </div>
  </div>
</div>

为什么这样有效?

  • 你之前给.grades_dashboard_m加Flex是让整个three_separation容器在父元素里居中,但这并不是你要解决的核心问题。
  • 给.grades_dashboard_box设置display: flex后,盒子内部的子元素(也就是<h1>)会遵循Flex的对齐规则:justify-content: center实现水平居中,align-items: center实现垂直居中,刚好匹配你盒子130px高度的垂直居中需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:41:44