需求:有时页面内的一些容器须要定位在特定的某个位置,可是须要容器在水平方向上面居中显示,好比页面内的一个背景图里面放置一个容器,使用margin-top不方便,就决定使用绝对定位来设置。web
实现方法:
方法1、知道容器尺寸的前提下浏览器
.element { width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; margin-top: -200px; /* 高度的一半 */ margin-left: -300px; /* 宽度的一半 */ }
缺点:该种方法须要提早知道容器的尺寸,不然margin负值没法进行精确调整,此时须要借助JS动态获取。code
方法2、容器尺寸未知的前提下,使用CSS3的transform属性代替margin,transform中的translate偏移的百分比值是相对于自身大小的,设置示例以下:orm
.element { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */ -webkit-transform: translate(-50%, -50%); }
缺点:兼容性很差,IE10+以及其余现代浏览器才支持。中国盛行的IE8浏览器被忽略是有些不适宜的(手机web开发可忽略)。element
方法3、margin: auto实现绝对定位元素的居中开发
.element { width: 600px; height: 400px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; /* 有了这个就自动居中了 */ }