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

如何在HTML Body中居中DIV?Flexbox使用疑问咨询

问题:使用Flexbox居中DIV时,元素出现在屏幕中心而非预期位置

刚开始学习CSS,遇到一个问题,若问题过于浅显还请见谅。我想要在HTML的body标签内居中一个DIV元素,尝试使用Flexbox布局实现,但不知为何该DIV出现在了屏幕中心。

我的代码如下:

<html lang="en">
    <body>
    <style type="text/css">
    
        body
        {
            background: #6CB3A9;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .main
        {
            width:300px;
            height:300px;
            background:white;
        }
    
    </style>
        <div class="main">
            <div class="white-bottom"></div>
            <div class="red-top"></div>
            <div class="yellow-center"></div>
        </div>
    </body>
    </html>

解答

你当前的代码里,body同时设置了两个Flexbox核心属性:

  • justify-content: center:控制水平方向的元素居中
  • align-items: center:控制垂直方向的元素居中

两者结合就会让.main元素同时在水平和垂直方向都居中,也就是屏幕的正中心位置。

场景1:仅需水平居中

如果你的需求只是让DIV在水平方向居中,直接移除align-items: center即可:

<html lang="en">
    <body>
    <style type="text/css">
    
        body
        {
            background: #6CB3A9;
            display: flex;
            justify-content: center;
            /* 移除垂直居中属性 */
        }
        .main
        {
            width:300px;
            height:300px;
            background:white;
        }
    
    </style>
        <div class="main">
            <div class="white-bottom"></div>
            <div class="red-top"></div>
            <div class="yellow-center"></div>
        </div>
    </body>
    </html>

场景2:需要全屏垂直居中

如果你的需求确实是要让元素在屏幕垂直居中,建议给body添加min-height: 100vh(占满视口高度),同时移除默认margin避免滚动条:

body
{
    background: #6CB3A9;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
}

内容的提问来源于stack exchange,提问作者saurabh-ar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:50:27