×

回顾移动端实现垂直居中的一些事

作者:shiji2018.03.13来源:Web前端之家浏览:12720评论:0
关键词:css移动端对齐

500.jpg

实现元素垂直居中的方法很多,相信大家都能说出几种。相对于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. }

上面的方法已经很齐全了,大家是可以试下咯,如果有更好的方法,可以留言分享出来哟(^U^)ノ~YO。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/duiqi213124124124.html

网友评论文明上网理性发言 已有0人参与

发表评论: