天天看點

移動端實作元素垂直居中的方法

實作元素垂直居中的方法很多,相信大家都能說出幾種。相對于PC端,移動端的方法會更多點,平時在網上收集了一些,在此貼出來分享給大家,僅供參考。

方法1:table-cell 

html結構

  1. <div class="box box1">
  2.     <span>垂直居中</span>
  3. </div>

 CSS

  1. .box1{    
  2.     display: table-cell;    
  3.     vertical-align: middle;    
  4.     text-align: center;            
  5. }

方法2:display:flex

  1. .box2{    
  2.     display: flex;    
  3.     justify-content:center;    
  4.     align-items:Center;
  5. }

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

  1. .box3{    
  2. position:relative;
  3. }
  4. .box3 span{           
  5.      position: absolute;          
  6.      width:100px;          
  7.      height: 50px;           
  8.      top:50%;           
  9.      left:50%;            
  10.      margin-left:-50px;            
  11.      margin-top:-25px;           
  12.      text-align: center;       
  13. }

方法4:絕對定位和0

  1. .box4 span{ 
  2.      width: 50%;   
  3.      height: 50%;    
  4.      background: #000; 
  5.      overflow: auto;   
  6.      margin: auto;   
  7.      position: absolute;   
  8.      top: 0; 
  9.      left: 0;
  10.      bottom: 0; 
  11.      right: 0;  
  12. }

這種方法跟上面的有些類似,但是這裡是通過margin:auto和top,left,right,bottom都設定為0實作居中。不過這裡得确定内部元素的高度,可以用百分比,比較适合移動端。

方法5:translate

  1. .box6 span{            
  2.     position: absolute;            
  3.     top:50%;            
  4.     left:50%;            
  5.     width:100%;            
  6.     transform:translate(-50%,-50%);            
  7.     text-align: center;        
  8. }

這實際上是方法3的變形,移位是通過translate來實作的。

方法6:display:inline-block

  1. .box7{  
  2.      text-align:center;  
  3.      font-size:0;}.box7 span{  
  4.      vertical-align:middle;  
  5.      display:inline-block;  
  6.      font-size:16px;}.box7:after{ 
  7.     content:'';  
  8.     width:0;  
  9.     height:100%; 
  10.     display:inline-block;  
  11.     vertical-align:middle;
  12. }

這種方法确實巧妙…通過:after來占位。

方法7:display:flex和margin:auto

  1. .box8{    
  2.     display: flex;    
  3.     text-align: center;
  4. }
  5. .box8 span{
  6.         margin: auto;
  7. }

方法8:display:-webkit-box

  1. .box9{   
  2.      display: -webkit-box;   
  3.      -webkit-box-pack:center;  
  4.      -webkit-box-align:center;   
  5.      -webkit-box-orient: vertical;    
  6.      text-align: center
  7. }

上面的方法已經很齊全了,大家是可以試下咯,如果有更好的方法,可以留言分享出來!