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

如何实现grid-container容器在页面中的垂直与水平居中?

实现grid-container在页面中垂直水平居中的调整方法

要让.grid-container同时实现页面内的垂直和水平居中,只需对现有CSS做两处关键修改:

修改步骤

  1. 调整body的布局与高度:
    给body设置min-height: 100vh确保其占满整个视口高度,同时添加flex布局并设置垂直排列方向,让header和grid-container能合理分配页面空间。
  2. 让grid-container自动居中:
    给.grid-container添加margin: auto,利用flex容器的特性实现自动垂直水平居中。

修改后的完整CSS代码

* {
  box-sizing: border-box;
  border: 0;
  list-style-type: none;
}

body {
  margin: auto;
  font-size: 16px;
  background-color: #9f95df;
  /* 新增:设置body占满视口高度并启用flex垂直布局 */
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

header {
  min-height: 15vh;
  width: 100%;
  display: flex;
  place-content: center;
  box-shadow: 10px 10px 5px 0px rgba(0, 0, 0, 0.35);
  -webkit-box-shadow: 10px 10px 5px 0px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 10px 10px 5px 0px rgba(0, 0, 0, 0.75);
  background-color: slateblue;
  color: #EEEEFF;
  text-shadow: 4px 4px 5px rgba(0, 0, 0, 0.9);
}

header span {
  font-size: normal;
  color: red;
}

.grid-container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-template-rows: 100px 100px;
  grid-gap: 3px;
  border: 1px solid red;
  place-content: center;
  /* 新增:让容器在flex父元素中自动居中 */
  margin: auto;
}

.grid-container div {
  background-color: orange;
}

原理说明

  • body设置min-height:100vh保证页面高度至少覆盖视口,flex-direction:column让子元素(header和grid-container)垂直排列;
  • margin:auto在flex容器中会自动将元素推向剩余空间的中心,同时实现水平和垂直方向的居中,无需额外设置justify-content或align-items。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:21:02