純CSS實(shí)現(xiàn)垂直居中的幾種方法

垂直居中是布局中十分常見(jiàn)的效果之一,為實(shí)現(xiàn)良好的兼容性,PC端實(shí)現(xiàn)垂直居中的方法一般是通過(guò)絕對(duì)定位,table-cell,負(fù)邊距等方法。有了css3,針對(duì)移動(dòng)端的垂直居中就更加多樣化。

方法1:table-cell

<div class="box box1">
        <span>垂直居中</span>
</div>

css:

.box1{
    display: table-cell;
    vertical-align: middle;
    text-align: center;        
}
box1.jpg

方法2:display:flex

.box2{
    display: flex;
    justify-content:center;
    align-items:Center;
}

方法3:絕對(duì)定位和負(fù)邊距

.box3{position:relative;}
.box3 span{
            position: absolute;
            width:100px;
            height: 50px;
            top:50%;
            left:50%;
            margin-left:-50px;
            margin-top:-25px;
            text-align: center;
        }

方法4:絕對(duì)定位和0

.box4 span{
  width: 50%; 
  height: 50%; 
  background: #000;
  overflow: auto; 
  margin: auto; 
  position: absolute; 
  top: 0; left: 0; bottom: 0; right: 0; 
}

這種方法跟上面的有些類似,但是這里是通過(guò)margin:auto和top,left,right,bottom都設(shè)置為0實(shí)現(xiàn)居中,很神奇吧。不過(guò)這里得確定內(nèi)部元素的高度,可以用百分比,比較適合移動(dòng)端。

方法5:translate

.box6 span{
            position: absolute;
            top:50%;
            left:50%;
            width:100%;
            transform:translate(-50%,-50%);
            text-align: center;
        }

這實(shí)際上是方法3的變形,移位是通過(guò)translate來(lái)實(shí)現(xiàn)的。

方法6:display:inline-block

.box7{
  text-align:center;
  font-size:0;
}
.box7 span{
  vertical-align:middle;
  display:inline-block;
  font-size:16px;
}
.box7:after{
  content:'';
  width:0;
  height:100%;
  display:inline-block;
  vertical-align:middle;
}

這種方法確實(shí)巧妙...通過(guò):after來(lái)占位。

方法7:display:flex和margin:auto

.box8{
    display: flex;
    text-align: center;
}
.box8 span{margin: auto;}

方法8:display:-webkit-box

.box9{
    display: -webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    -webkit-box-orient: vertical;
    text-align: center
}

css3博大精深,可以實(shí)現(xiàn)很多創(chuàng)造性的效果,需要好好研究下。

方法9:display:-webkit-box

這種方法,在 content 元素外插入一個(gè) div。設(shè)置此 div height:50%; margin-bottom:-contentheight;。

content 清除浮動(dòng),并顯示在中間。

<div class="floater"></div>  
<div class="content"> Content here </div>  

.floater {
    float:left; 
    height:50%; 
    margin-bottom:-120px;
}
.content {
    clear:both; 
    height:240px; 
    position:relative;
}

優(yōu)點(diǎn):
適用于所有瀏覽器
沒(méi)有足夠空間時(shí)(例如:窗口縮小) content 不會(huì)被截?cái)?,滾動(dòng)條出現(xiàn)
缺點(diǎn):
唯一我能想到的就是需要額外的空元素了

用心寫(xiě)代碼,不辜負(fù)程序員之名。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容