css實現水平/垂直居中效果


一、如果是已知寬高的元素做水平/垂直居中效果的話,可以直接用具體的數值指定定位布局或偏移布局,這個就不過多討論。這里主要介紹在不知寬高或需要彈性布局下的幾種實現方式。

二、
1.table表格法
思路:顯示設置父元素為:table,子元素為:cell-table,vertical-align: center
優點:父元素(parent)可以動態的改變高度(table元素的特性)
缺點:IE8以下不支持
代碼實現:

.parent1{
    display: table;
    height:300px;
    width: 300px;
    background-color: red;
}
.parent1 .child{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    color: #fff;
    font-size: 16px;
}

</style>
<body>
    <div class="parent1">
        <div class="child">hello world-1</div>
    </div>
</body>

效果:

 

2.空元素法
思路:使用一個空標簽span設置他的vertical-align基准線為中間,並且讓他為inline-block,寬度為0
缺點:多了一個沒用的空標簽,display:inline-blockIE 6 7是不支持的(添加上:_zoom1;*display:inline)。當然也可以使用偽元素來代替span標簽,不過IE支持也不好

代碼實現:

<style>
.parent2{
    height:300px;
    width: 300px;
    text-align: center;
    background: red;
}
.parent2 span{
    display: inline-block;;
    width: 0;
    height: 100%;
    vertical-align: middle;
    zoom: 1;/*BFC*/
    *display: inline;
}
.parent2 .child{
    display: inline-block;
    color: #fff;
    zoom: 1;/*BFC*/
    *display: inline;
}

</style>
<body>

    <div class="parent2">
        <span></span>
        <div class="child">hello world-2</div>
    </div>
</body>

效果:

 

3.-50%定位法
思路:子元素絕對定位,距離頂部 50%,左邊50%,然后使用css3 transform:translate(-50%; -50%)
優點:高大上,可以在webkit內核的瀏覽器中使用
缺點:不支持IE9以下不支持transform屬性

代碼實現:

<style>
.parent3{
    position: relative;
    height:300px;
    width: 300px;
    background: red;
}
.parent3 .child{
    position: absolute;
    top: 50%;
    left: 50%;
    color: #fff;
    transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent3">
        <div class="child">hello world-3</div>
    </div>
</body>

效果:

 

4.思路:使用css3 flex布局法
優點:簡單 快捷
缺點:低端pc瀏覽器和低版本的安卓設備不支持,不過現在應該很少用了

代碼實現:

<style>
.parent4{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 300px;
    height:300px;
    background: red;
}
.parent4 .child{
    color:#fff;
}
</style>
<body> 
    <div class="parent4">
        <div class="child">hello world-4</div>
    </div>
</body>

效果:

5.絕對定位法
思路:父元素使用定位(相對/絕對都行),子元素設置position:absolute; top: 0; left: 0; bottom: 0; right: 0; margin:auto;
優點:兼容性好,父元素寬高可變,使用非常靈活,在做全屏居中的時候很好
缺點:子元素還是要指定寬高,可以用百分比

代碼實現:

.parent5{
    position:absolute;
    width: 300px;
    height:300px;
    background: red;
}
.parent5 .child{
    color:#fff;
    margin: auto;
    position:absolute;
    top:0;
    left:0;
      right:0;
      bottom:0;
      text-align:center;
      width:50%;
    height:20%;
}
</style>
<body> 
    <div class="parent5">
        <div class="child">hello world-5</div>
    </div>
</body>

 

效果:

 

三、在追逐性能時代,現在基本都是webkit內核了,擁抱css3彈性布局,個人比較推薦用4、5方法,4.flex布局法適合在局部使用。5.絕對定位法適合在全屏場景使用,比如彈框中。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM