css实现水平居中的方法
来源:互联网 发布:对数据进行加工与处理 编辑:程序博客网 时间:2024/05/22 14:49
一直想写一篇关于水平居中的文章,因为水平居中是平时写界面最常用到的。那么如何实现呢,我根据自己的经验以及网上的经验,做了一个小小的总结。
方案一: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 0
- css实现水平居中的方法
- css实现垂直居中和水平居中的方法
- css 水平居中的方法
- css水平居中的方法
- Div和CSS实现页面水平居中的方法
- Css实现垂直和水平居中的方法
- 使图片垂直&水平居中的CSS实现方法
- 用css实现垂直水平居中的几种方法
- CSS实现元素水平/垂直居中的方法
- 【css】实现垂直水平居中的几种方法
- CSS实现水平垂直居中的几种方法
- css实现水平垂直居中的几种方法
- css实现div的水平垂直居中方法
- css实现垂直水平居中的5种方法
- css实现水平居中的几种方法
- 【CSS总结】CSS水平居中的方法
- css居中的实现方法(包括水平居中和垂直居中)
- CSS实现水平垂直居中方法总结
- U盘路径,SD卡路径
- ngx_queue_t
- QML中的ECMAscript
- 探究ArrayList 和Map 的读取和插入效率
- Raising Modulo Numbers
- css实现水平居中的方法
- quote symbol expected
- Unexpected internal error near index 1
- QML中信号槽机制的使用
- ASP.NET MVC3实战系列(一):简单示例
- 在ubuntu上安装RapidMiner
- 用户组:Stuff和Wheel组区别
- Codeforces 651D Image Preview【二分+枚举】
- Linux 文件系统与设备文件系统 (一)—— udev 设备文件系统