直接上代码。。。
1.绝对居中(水平和垂直方向都居中)
<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>
在IE下测试:
在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>
猎豹浏览器下测试:
(---------------完---------------)