元素水平垂直居中的方法

元素水平垂直居中的方法

方法一:(利用定位,子元素绝对定位,父元素相对定位,子元素left、right、top、bottom都为0、margin:auto)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{padding: 0;margin: 0;}
        .wrap{
            width: 800px;
            height: 500px;
            border:1px solid #000;
            margin:0 auto;
            position: relative;
        }
        .sub{
            width: 400px;
            height: 300px;
            background-color: red;
            border:1px solid #000;
            position: absolute;
            left:0;
            right:0;
            top:0;
            bottom:0;
            margin:auto;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="sub"></div>
    </div>
</body>
</html>

方法二:(利用 定位 和CSS3的属性,子元素绝对定位、父元素相对定位、子元素left:50%、top:50%、transform: translate(-50%, -50%) ) ,推荐的用法

  优点:不用计算父级元素宽度的大小

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{padding: 0;margin: 0;}
        .wrap{
            width: 800px;
            height: 500px;
            border:1px solid #ccc;
            margin:0 auto;
            position: relative;
        }
        .sub{
            width: 400px;
            height: 300px;
            background-color: #66f;
            border:1px solid #000;
            position: absolute;
            left:50%;
            top:50%;
            transform:translateX(-50%) translateY(-50%);
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="sub"></div>
    </div>
</body>
</html>

 方法三:(利用 定位 和margin ,子元素绝对定位,父元素相对定位, 子元素left:50%, top:50%,margin-left:-自身宽度的1/2; margin-top: -自身高度的1/2; )

  缺点:需要计算margin-left 和 margin-top,后期维护的时候不方便

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{padding: 0;margin: 0;}
        .wrap{
            width: 800px;
            height: 500px;
            border:1px solid #000;
            margin:0 auto;
            position: relative;
        }
        .sub{
            width: 400px;
            height: 300px;
            background-color: #66f;
            border:1px solid #000;
            position: absolute;
            left:50%;
            top:50%;
            margin-left:-201px;
            margin-top:-151px;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="sub"></div>
    </div>
</body>
</html>
作者:David-lcw
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/david-lcw/p/10466046.html