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