CSS实现垂直居中

1.flex布局

先渲染出一个正方形

<body>
    <div class="box"></div>

</body>
<style>
   .box{
             300px;
            height: 300px;
            background-color: red;
            
        }
</style>

将元素的父类设置flex布局

<style>
  html,body{
             100%;
            height: 100%;
            margin: 0;
            padding: 0;
          
        }
        body{
            display: flex;
            justify-content: center;
            align-items: center;
        }
</style>

效果如图

2.定位

    <style>
        html,body{
             100%;
            height: 100%;
            margin: 0;
            padding: 0;
          
        }
    

        .box{
             300px;
            height: 300px;
            background-color: red;
            margin: 0 auto; //实现水平居中
            position: relative;//相对定位
            top: calc(100vh/2);//顶部高度为屏幕的一半
            transform: translateY(-50%);//沿Y周向上移元素的一半
        }
    </style>
原文地址:https://www.cnblogs.com/babilong/p/13441937.html