css絕對定位居中的實現方法有很多,下面將給大家介紹css絕對定位居中的四種方法。
1、兼容性不錯的主流css絕對定位居中的用法:
.conter{
width:600px;height:400px;
position:absolute;left:50%;top:50%;
margin-top:-200px;/*高度的一半*/
margin-left:-300px;/*寬度的一半*/
}
注意:這種方法有一個很明顯的不足,就是需要提前知道元素的尺寸。否則margin負值的調整無法精確。此時,往往要藉助JS獲得。
2、css3的出現,使得有了更好的解決方法,就是使用transform代替margin.transform中translate偏移的百分比值是相對於自身大小的,可以這樣實現css絕對定位居中:
.conter{
width:600px;height:400px;
position:absolute;left:50%;top:50%;
transform:translate(-50%,-50%);/*50%爲自身尺寸的一半*/
}
3、margin:auto實現絕對定位元素的居中(上下左右均0位置定位;margin:auto)
.conter{
width:600px;height:400px;
position:absolute;left:0;top:0;right:0;bottom:0;
margin:auto;/*有了這個就自動居中了*/
}