CSS各种居中姿势

本文转至http://www.html5dw.com/post?id=1433

水平居中:行内元素解决方案
       只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可:

[css]  view plain  copy
  1. .parent {  
  2.      display:flex;  
  3.      justify-content:center;  
  4.   }  

垂直居中:未知高度的块状元素解决方案

[css]  view plain  copy
  1. .item{  
  2.         
  3.   top: 50%;  
  4.        
  5.   positionabsolute;  
  6.       
  7.   transform: translateY(-50%);  /* 使用css3的transform来实现 */  
  8.    
  9. }  

水平垂直居中:未知高度和宽度元素解决方案

[css]  view plain  copy
  1. .item{  
  2.        
  3.   positionabsolute;  
  4.       
  5.   top: 50%;  
  6.      
  7.   left: 50%;  
  8.       
  9.   transform: translate(-50%-50%);  /* 使用css3的transform来实现 */  
  10.   
  11. }  


水平居中:行内元素解决方案
       只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可:

[css]  view plain  copy
  1. .parent {  
  2.     text-align:center;  
  3.   }  

水平居中:块状元素解决方案
[css]  view plain  copy
  1. .item {  
  2.      /* 这里可以设置顶端外边距 */  
  3.      margin10px auto;  
  4.    }  

垂直居中:多行的行内元素解决方案
组合使用display:table-cell和vertical-align:middle属性来定义需要居中的元素的父容器元素生成效果,如下:
[css]  view plain  copy
  1. .parent {  
  2.   
  3.     background#222;  
  4.       
  5.     width300px;  
  6.       
  7.     height300px;  
  8.       
  9.     /* 以下属性垂直居中 */  
  10.       
  11.     displaytable-cell;  
  12.       
  13.     vertical-align:middle;  
  14.     
  15.   }  

水平垂直居中:已知高度和宽度的元素解决方案1

       这是一种不常见的居中方法,可自适应,比方案2更智能,如下:

[css]  view plain  copy
  1. .item{  
  2.           
  3.     positionabsolute;  
  4.         
  5.     margin:auto;  
  6.        
  7.     left:0;  
  8.        
  9.     top:0;  
  10.          
  11.     right:0;  
  12.        
  13.     bottom:0;  
  14.     
  15.   }  

水平垂直居中:已知高度和宽度的元素解决方案2

[css]  view plain  copy
  1. .item{  
  2.          
  3.    positionabsolute;  
  4.         
  5.    top: 50%;  
  6.        
  7.    left: 50%;  
  8.         
  9.    margin-top-75px;  /* 设置margin-left / margin-top 为自身高度的一半 */  
  10.         
  11.    margin-left-75px;  
  12.      
  13.  }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值