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

水平居中
(1)使用inline-block+text-align
<div class="parent">
<div class="child">demo</div>
</div>

    .child {
             display:inline-block;
        }
        .parent {
             text-align:center
        }

    原理:先將子框由塊級元素改變爲行內塊元素,再通過設置行內塊元素居中以達到水平居中。
    優點:兼容性好,甚至可以兼容ie6、ie7

    (2)使用table+margin
        .child {
            display:table
            margin:0 auto;
        }
原理:先將子框設置爲塊級表格來顯示,再設置子框居中以達到水平居中。
缺點:不支持ie6、ie7,將div換成table

(3)使用absolute+transform
    .child {
                 position:absolute;
                 left:50%;
                 transform:translateX(-50%)
        }
        .parent {
                  position:relative
        }

缺點:transform屬於css3內容,兼容性存在一定問題,高版本瀏覽器需要添加一些前綴

(4)使用flex+margin
        .child {
          margin:0 auto
        }
        .parent {
                display:flex
        }
缺點:低版本瀏覽器(ie6 ie7 ie8)不支持

(5)使用flex+justify-content
    .parent {
                display:flex;
                justify-content:center
        }
    缺點:低版本瀏覽器(ie6 ie7 ie8)不支持

    垂直居中
    (1)使用table-cell+vertical-align

        .parent {
                display:table-cell;
                vertical-align:middle
        }

    (2)使用absolute+transform
        .child {
          position:absolute;
            top:50%;
            transform:translateY(-50%)
        }
        .parent {
                position:relative
        }
缺點:transform屬於css3內容,兼容性存在一定問題,高版本瀏覽器需要添加一些前綴

    (3)使用flex+align-items
        .parent {
            display:flex;
            align-items:center;
        }

    水平垂直居中
    (1)使用absolute+transform(未知高度)
    .parent {
            position:relative;
        }
    .child {
            position:absolute;
            left:-50%;
            top:-50%
            transform:translate(-50%,-50%)
        }
    (1.1)使用absolute+transform(已知高度)
    .parent {
            position:relative;
        }
    .child {
            position:absolute;
            width:100px;
            height:100px;
            left:-50%;
            top:-50%
          margin: -50px 0 0 -50px;
        }

        (2)使用inline-block+text-align+table-cell+vertical-align
        .parent {
            text-align:center;
            display:table-cell;
            vertical-align:middle;
        }
        .child {
                display:inline-block;
        }
        優點:兼容性較好

        (3)使用flex+justify-content+align-items
        .parent {
            display:flex;
            justify-content:center;
            align-items:center;
        }
        缺點:兼容性存在一定問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章