純CSS實現垂直居中的幾種方法

垂直居中是佈局中十分常見的效果之一,爲實現良好的兼容性,PC端實現垂直居中的方法通常是經過絕對定位,table-cell,負邊距等方法。有了css3,針對移動端的垂直居中就更加多樣化。css

方法1:table-cell

html結構:html

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

css:css3

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

方法2:display:flex

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

方法3:絕對定位和負邊距

.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:絕對定位和0

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

這種方法跟上面的有些相似,可是這裏是經過margin:auto和top,left,right,bottom都設置爲0實現居中,很神奇吧。不過這裏得肯定內部元素的高度,能夠用百分比,比較適合移動端。佈局

方法5:translate

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

這其實是方法3的變形,移位是經過translate來實現的。flex

相關文章
相關標籤/搜索