如何实现div垂直居中的四种方法

第一种:给父级设置宽高100%,div设置绝对定位,left,right,top,bottom设置为0,margin:auto即可实现

//布局  style
*{
     margin: 0;
     padding: 0; 
 }
 body,html{
      width: 100%;
      height: 100%;
      position: relative;
 }
 .div{
      position: absolute;
      width: 200px;
      height: 200px;
      background: salmon;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
 }
//body
<body>
    <div class="div"></div>
</body>

第二种:利用绝对定位和tranform(过渡动画)实现,div绝对定位,left: 50%; top: 50%;然后设置 transform: translate3d(-50%,-50%,0);即可

<style>
        *{
            margin: 0;
            padding: 0;
        }
        body,html{
            width: 100%;
            height: 100%;
            position: relative;
        }
        .div{
            position: absolute;
            width: 200px;
            height: 200px;
            background: salmon;
            left: 50%;
            top: 50%;
            transform: translate3d(-50%,-50%,0);
        }
    </style>
//body
<body>
    <div class="div"></div>
</body>

第三种:flex弹性盒布局,给父级div设置display:flex,设置水平和垂直居中 justify-content: center; align-items: center;

//style
.div{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.box{
    width: 200px;
    height: 200px;
    background: sandybrown;
}
//body
<body>
    <div class="div">
        <div class="box"></div>
    </div>
</body>

第四种:div设置绝对定位,left: 50%; top: 50%距离左和上是margin-left:calc(-div自身宽度/2),margin-top:calc(-div自身高度/2),也可以自己计算margin-left和margin-top的值

//style
<style>
        *{
            margin: 0;
            padding: 0;
        }
        body,html{
            width: 100%;
            height: 100%;
            position: relative;
        }
        .div{
            position: absolute;
            width: 200px;
            height: 200px;
            background: salmon;
            left: 50%;
            top: 50%;
            margin-left:calc(-200px/2);
            margin-top: calc(-200px/2);
        }
    </style>
//body
<div class="div">
        <div class="box"></div>
    </div>

以上就是四种方法的实现
有不对的请指教~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容