css 在HMTL主体内居中DIV [副本]

x6yk4ghg  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(89)

此问题在此处已有答案

How can I vertically center a div element for all browsers using CSS?(48个答案)
8小时前关门了。
我刚开始学习CSS,就遇到了这个问题。如果我问这个问题太傻了,请原谅。
我想在主体标签内居中一个DIV。我厌倦了使用FlexBox来做这个,但不知何故它出现在屏幕的中心。
下面是代码。

<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>
qoefvg9y

qoefvg9y1#

在主体上设置display: flex, justify-content: center; align-items: center;
这将使用flex-box使内容垂直和水平居中:)

sqserrrh

sqserrrh2#

如果使用display: flex;,则不需要align-items: center;
注意:我为body设置了一个height,以证明它水平地位于body标记的中心。

<html lang="en">
    <body>
    <style type="text/css">
    
        body
        {
            background: #6CB3A9;
            display: flex;
            justify-content: center;
            // align-items: center;
            height: 500px;
            border: 1px solid grey
        }
        .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>

相关问题