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

Mozilla Flex Box居中代码仅实现水平居中问题求助

Fixing Vertical Centering with Flexbox

Hey there! I totally get why you're confused—your flex code looks right on paper, but it's not working vertically. Let's break down the issue and fix it.

The Root Cause

Your flex container (.box) only takes up the height of its child element by default. Without extra vertical space inside the container, align-items: center doesn't have any room to do its job—that's why you only see horizontal centering.

The Fix

We need to give the flex container a defined vertical height so there's space to center the child. Here's how to do it properly:

Step 1: Make the Container Fill the Viewport

Add height: 100vh to .box to make it take up the full height of the browser window. We'll also reset the default body margin to avoid unwanted spacing or scrollbars.

Full Working Code

/* Reset default browser styles to eliminate extra spacing */
body {
  margin: 0;
}

.box {
  display: flex;
  align-items: center;    /* Handles vertical centering */
  justify-content: center;/* Handles horizontal centering */
  height: 100vh;          /* Make container span full viewport height */
}

.box div {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div class="box">
  <div></div>
</div>

If You Need Centering Inside a Parent Element

If your .box is nested inside another container instead of the body, you need to ensure all parent elements up to html have a defined height (since percentage heights rely on a parent with a fixed height):

html, body {
  height: 100%;
  margin: 0;
}

.parent-container {
  height: 100%; /* Fill the height of its parent (body) */
}

.box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%; /* Fill the height of its parent (.parent-container) */
}

That should get your red div perfectly centered both horizontally and vertically!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:47:25