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

如何使用CSS Grid实现文本水平居中?附代码与示例参考

问题排查与修复

你当前代码和目标效果有两处核心差异:

  • 网格子元素仅设置了水平居中,缺少垂直居中的样式配置
  • 默认的从左到右、从上到下的元素排列顺序和示例要求的相反,当前输出第一行是1、2、3、4,第二行是5、6、7、8,和示例顺序完全颠倒

以下是修改后的完整代码,HTML部分无需调整,仅修改CSS即可:

* {
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.grid {
  background-color: #ddd;
  padding: 20px;
  width: 800px;
  height: 400px;
  margin: auto;
  display: grid;
  grid-template-columns: auto 1fr 1fr auto;
  grid-template-rows: 1fr auto;
  gap: 20px;
  /* 反转行排列顺序,让原本的第二行移到第一行位置 */
  grid-auto-flow: row-reverse;
  /* 反转列排列顺序,让每行内的元素从右往左排 */
  direction: rtl;
}

.grid div {
  background: #403f3f;
  color: white;
  /* 实现内容垂直+水平居中 */
  display: flex;
  align-items: center;
  justify-content: center;
  /* 修复父级rtl导致的数字显示方向问题 */
  direction: ltr;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:09:00