使用css的绝对定位来控制页面居中的方法之一

直接上代码。。。

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>
猎豹浏览器下测试:



(---------------完---------------)







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值