DIV+CSS实现盒子居中的几种方法比较(考虑兼容性)
来源:互联网 发布:淘宝 武士刀 编辑:程序博客网 时间:2024/06/07 15:44
例子中html代码如下:
<div class="center"></div>
为了让结果更清晰加上如下的css样式
.center{ width:100px; height: 100px; background-color: gray;}
1. 实现水平居中
1) margin: 0 auto——IE6-8,chrome和mozilla测试有效
这是常用的方法,该方法兼容IE6-8,chrome和mozilla
2) 父元素设置text-align: center——但是该方法只适用于IE6,IE7
例如设置:
body{ text-align: cenert;}
3) 利用position:absolute和margin——IE6-8,chrome和mozilla测试有效
.center{ position: absolute; left: 50%; margin-left: -50%;}
这里用left:50%使div的左边界距离窗口50%,但是需要向左移动50%的width(div本身的宽度)才能真正实现水平居中;也可以替换left和margin-left:
.center{ position: absolute; margin-left: 50%; left: -50px;}
2. 实现水平垂直居中
1) 利用position: absolute和margin:auto——兼容IE8,chrome和mozilla,但是不兼容IE6-7
.center{ position: absolute; top:0; bottom:0; left:0; right:0; margin: auto;}
可能有人认为利用margin: 0 auto可以实现水平居中, 那么margin: auto 0和margin: auto可以分别实现垂直居中和水平垂直居中,但是其实是错误的。前者无法实现居中,而后者也只能实现水平居中。但是配合position: absolute就能实现水平垂直居中。 2) 利用position: absolute和margin——IE6-8,chrome和mozilla测试有效
.center{ position: absolute; left: 50%; margin-left: -50px; left: 50%; margin-left: -50px;}
<div class="container"> <div class="center"></div></div>
css:.container{ width:500px; height:500px; background:yellow; display: flex;}.center{ width:100px; height:100px; background:gray; margin:auto}
阅读全文
0 0
- DIV+CSS实现盒子居中的几种方法比较(考虑兼容性)
- CSS盒子居中的几种方法
- div盒子水平居中垂直居中的几种方法
- css 实现div垂直居中的几种方法
- 垂直居中的几种方法比较(纯CSS)
- 实现div居中的几种方法
- css未盒子div居中的多种方法
- 屏幕居中(DIV/CSS) 的几种方法
- div盒子在页面中水平垂直居中的几种方法。
- css 几种水平垂直居中的方法 及 弹性盒子
- 实现div水平、垂直居中的几种方法
- div盒子水平垂直居中的方法
- div盒子水平垂直居中的方法
- div盒子水平垂直居中的方法
- CSS实现垂直居中的几种方法
- CSS实现垂直居中的几种方法
- 用css实现垂直水平居中的几种方法
- CSS实现垂直居中的几种方法
- Cg内置函数
- Javascript第五天学习总结之Dom节点
- FileWiter --文件输出字符流
- 数据结构之Trie树
- MATLAB三维插值作曲面图 等高线图
- DIV+CSS实现盒子居中的几种方法比较(考虑兼容性)
- Express Install
- 存储过程分页
- Shopping 倍增
- SWPU暑假第一场训练赛题解
- html dom创建表格
- Python入门8_方法,属性,迭代器
- BZOJ1691: [Usaco2007 Dec]挑剔的美食家
- TabLayout+ViewPager使用