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

如何通过Flex或Grid实现main元素在body中垂直水平居中?

解决main元素在屏幕上垂直+水平居中的问题

你遇到的核心问题是body默认没有占满整个视口高度,直接给body加grid/flex居中属性时,垂直方向没有足够空间生效。以下是两种可靠的解决方案:

Grid 方案

先给html和body设置最小高度占满视口,再通过grid布局实现居中:

html, body {
  margin: 0; /* 清除默认边距,避免多余留白 */
  min-height: 100vh; /* 让容器至少占满整个视口高度 */
}

body {
  display: grid;
  place-content: center;
}

Flex 方案

同样确保容器高度,再用flex布局的双轴居中属性:

html, body {
  margin: 0;
  min-height: 100vh;
}

body {
  display: flex;
  justify-content: center; /* 水平方向居中 */
  align-items: center; /* 垂直方向居中 */
}

关键说明

  • 必须设置min-height: 100vh(或height: 100%,但vh更适配视口),否则body高度仅由内部内容撑开,垂直居中无法生效。
  • 清除body的默认margin,避免出现滚动条或不必要的空隙。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:37:14