css实现水平居中的方法

一直想写一篇关于水平居中的文章,因为水平居中是平时写界面最常用到的。那么如何实现呢,我根据自己的经验以及网上的经验,做了一个小小的总结。

方案一:margin方法

最简单的margin方法:

.center {
    width: 960px;
    /*如果你想做自适应,可以把宽度设为百分比*/
    margin:0 auto;
}

优点:实现方法简单易懂,浏览器兼容性强;

缺点:扩展性差

方案二:inline-block实现水平居中方法

仅inline-block属性是无法让元素水平居中,他的关键之处要在元素的父容器中设置text-align的属性为“center”,这样才能达到

.father {
  text-align: center;
}
.child {
  margin: 0 5px;
  display: inline-block;
  *display: inline;
}

通常我用这个属性的时候就是直接

*{
 text-align: center;
}

然后看哪些元素不会自动居中,再通过margin或者其他方法设置,其实这样很麻烦,因为没有设置过inline-block,回头好好研究一下inline-block。
做点:简单易懂,扩展性强;

缺点:需要额外处理inline-block的浏览器兼容性。

方案三:绝对定位实现水平居中

也是非常常见的一款居中方式:

.father{
       position:relative;
}
.child{
    position: absolute;
    width: 宽度值;
    left: 50%;
    margin-left: -(宽度值/2);
}   

以下是摘录自w3plus的代码,我也不知道为什么li必须为relative,还说大家懂的。。。有时间自己试一下呢

.pagination {
  position: relative;
}
.pagination ul {
  position: absolute;
  left: 50%;
}
.pagination li {
  line-height: 25px;
  margin: 0 5px;
 float: left;
  position: relative;/*注意,这里不能是absolute,大家懂的*/
  right: 50%;
}
.pagination a {
  display: block;
  color: #f2f2f2;
  text-shadow: 1px 0 0 #101011;
  padding: 0 10px;
  border-radius: 2px;
  box-shadow: 0 1px 0 #5a5b5c inset,0 1px 0 #080808;
  background: linear-gradient(top,#434345,#2f3032);
}
.pagination a:hover {
  text-decoration: none;
  box-shadow: 0 1px 0 #f9bd71 inset,0 1px 0 #0a0a0a;
  background: linear-gradient(top,#f48b03,#c87100);
}   

下面这几种都是我不常用的,所以也就不写了,感觉上面几种常用方法就够了。
下面这几种留着我有时间再去探讨。

方案四:CSS3的flex实现水平居中方法

方案五:CSS3的fit-content实现水平居中方法

方案六:浮动实现水平居中的方法

出处:http://www.w3cplus.com/css/elements-horizontally-center-with-css.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值