html 中 div 盒子上下垂直居中显示

前言

日常开发中经常遇到内容水平与垂直居中,不管是文字、图片,我们都把它们放进一个 div 盒子里来操作。

画一个盒子

<!DOCTYPE html>
<html lang="en">
    <body>
        <div class="child"></div>
    </body>
    <style>
        html {
      
      
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100vh;
            background-color: #457b9d;
            box-sizing: border-box;
        }
        body {
      
      
            padding: 0;
            margin: 0;
        }
        .child {
      
      
            background-color: #1d3557;
            width: 200px;
            height: 200px;
        }
    </style>
</html>

初始盒子展示

在这里插入图片描述

使用 flex 居中盒子

在父容器里面增加如下代码

            display: flex;
            /* 水平居中 */
            align-items: center;
            /* 垂直居中 */
            justify-content: center;

具体如下

        html {
    
    
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100vh;
            background-color: #457b9d;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
        }

效果图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Fine_Cui/article/details/125036590