欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

四招让你轻松搞定div元素的垂直居中对齐

最编程 2024-08-08 19:04:57
...

第一种:给父级设置宽高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>

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