水平垂直居中幾種實現方式

未知寬高的元素實現水平垂直居中html

方法一:父元素display:table; 子元素:display:cell-tableweb

優點,父元素能夠動態改變高度佈局

劣勢:table屬性容易形成屢次reflow,IE8如下不支持flex

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .parent1{
            display:table;
            height:300px;
            width:300px;
            background-color:#FD0c70;
        }
        .parent1 .child{
            display:table-cell;
            vertical-align:middle;
            text-align:center;
            color:#fff;
            font-size:16px;
        }
    </style>
</head>
<body>
    <div class="parent1">
        <div class="child">hello world</div>
    </div>
</body>
</html>

方法二:利用空元素和僞類:code

優勢:兼容性好orm

缺點:多出來個空元素,麻煩htm

如下代碼的註釋部分是替代after僞類的另外一種寫法,原理同樣it

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .parent{
            position:absolute;
            width:100%;
            height:100%;
            text-align:center;
            background:#92b922;
        }
        .child{
            background:#d93168;
            display:inline-block;
            color:#fff;
            padding:20px;
        }
        .parent:after{
            display:inline-block;
            content:'';
            width:0px;
            height:100%;
            vertical-align:middle;
        }
      /*  .vamb{
            display:inline-block;
            width:0px;
            height:100%;
            vertical-align:middle;
        }*/
    </style>
</head>
<body>
    <div class="parent">
      <!--   <b class="vamb"></b> -->
        <div class="child">hello world</br>hello world</div>
    </div>
</body>
</html>

方法三,絕對定位+transformio

優勢:方便,支持webkit內核table

缺點:transform兼容性差,IE9如下不支持

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .parent{
            position:relative;
            width:300px;
            height:300px;
            background:#92b922;
        }
        .child{
            position:absolute;
            top:50%;
            left:50%;
            color:#fff;
            background:red;
            transform:translate(-50%,-50%);
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">hello world</br>hello world</div>
    </div>
</body>
</html>

方法四,flex佈局

優勢:方便

缺點:兼容性很差,IE支持不好

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .parent{
            display:flex;
            justify-content:center;
            align-items:center;
            width:300px;
            height:300px;
            background:#92b922;
        }
        .child{
            color:#fff;
            background:red;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">hello world</br>hello world</div>
    </div>
</body>
</html>
相關文章
相關標籤/搜索