您的位置:首页 > Web前端 > CSS

css实现水平居中的方法

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

方案一: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实现水平居中方法

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

出处:/article/1214595.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: