使用css的絕對定位來控制頁面居中的方法之一
阿新 • • 發佈:2019-01-28
直接上程式碼。。。
1.絕對居中(水平和垂直方向都居中)
在IE下測試:<html> <head> <style type="text/css"> #main{ /*css只有這種註釋方法,不能用雙斜線註釋,否則會發生你意想不到的問題*/ position:absolute; left:50%; /*left設定為50%,這時是以元素的左側進行的水平居中,所以需要設定margin-left為元素寬度的一半:-200px;*/ top:50%; /*top設定為50%, 這時是以元素的上邊進行的垂直居中,所以需要設定margin-top為元素寬度的一半:-200px;*/ margin-top:-200px; margin-left:-200px; width:400px; height:400px; background-color:green; } #child{ width:200px; height:200px; position:absolute; left:20px; top:50px; background-color:yellow; border:1px solid blue; } </style> </head> <body style="text-align:center;"> <div id="main"> <div id="child"> </div> </div> </body> </html>
在Firefox瀏覽器下測試:
在獵豹瀏覽器下測試:
在360瀏覽器下測試:
從上面的效果來看,這個方法的相容性還是很高的。
2.水平居中(即只是水平方向居中)
獵豹瀏覽器下測試:<html> <head> <style type="text/css"> #main{ /*css只有這種註釋方法,不能用雙斜線註釋,否則會發生你意想不到的問題*/ position:absolute; left:50%; /*left設定為50%,這時是以元素的左側進行的水平居中,所以需要設定margin-left為元素寬度的一半:-200px;*/ margin-left:-200px; width:400px; height:400px; background-color:green; } #child{ width:200px; height:200px; position:absolute; left:20px; top:50px; background-color:yellow; border:1px solid blue; } </style> </head> <body style="text-align:center;"> <div id="main"> <div id="child"> </div> </div> </body> </html>
(---------------完---------------)