元素水平垂直居中的方法

元素水平垂直居中的方法

方法一:(利用定位,子元素绝对定位,父元素相对定位,子元素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>

 

posted @ 2019-03-03 16:02  David-lcw  阅读(261)  评论(0)    收藏  举报
My Google PageRank