标签:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>盒子居中</title>
<style>
#box1{
width:200px;
height:200px;
padding:100px;
border:1px solid black;
position:absolute;
top:50%;
left:50%;
margin-top:-201px;
margin-left:-201px;
}
h1{
text-align:center;}
</style>
</head>
<body>
<div id="box1">
<h1>我要居中</h1>
</div>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> #box1{ width:200px; height:200px; padding:100px; border:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; margin:auto; } h1{ text-align:center;} </style> </head> <body> <div id="box1"> <h1>我要居中</h1> </div> </body> </html>
这两种方法都是让一个盒子在浏览器窗口居中。
第一种方法:先设置绝对定位,top和left的值都设置为50%。再把盒子的margin-top设置为盒子高度的一半,margin-left设置为盒子宽度的一半即可(注意这里的值都是负的)。
第二种方法:也是通过绝对定位,不过这里把top,right,left,bottom的值都设置为0,再设置marign:auto。盒子自然而然就居中了。
标签:
原文地址:http://www.cnblogs.com/rareearth/p/5406473.html