1、兼容性不错的主流css绝对定位居中的用法:
.conter{
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
这种方法有一个很明显的不足,就是需要提前知道元素的尺寸。否则margin负值的调整无法精确。此时,往往要借助JS获得。
2、使用transform代替margin:
.conter{
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%);
}
transform中translate偏移的百分比值是相对于自身大小的,可以这样实现css绝对定位居中。
3、margin:auto实现绝对定位元素的居中
.conter{
width: 600px; height: 400px;
position: absolute; left: 0; top: 0; right: 0; bottom: 0;
margin: auto;
}
网友评论