我们知道 div 的 position 属性是支持百分比数值来进行定位的,有了这个定位能力,我们就可以把 div 的显示坐标定位在网页的绝对中心了,再通过 margin 属性把 div 设置为我们需要的宽度和高度就可以。当然我们的 margin-top 和 margin-left 属性需要使用到负数,把DIV的定位从中心分别向上和向左移动到合适的地方。下面这个例子可以在页面上建立一个垂直水平居中的 DIV:
<!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>垂直水平居中的 DIV</title>
<style type="text/css">
#pageFrame {
position: absolute; // 设置为绝对定位
left: 50%; // 设置显示坐标 X
top: 50%; // 设置显示坐标 Y
width:760px; // 设置 DIV 宽度
background:#EEE;
}
</style>
</head>
<body>
<div id="pageFrame">垂直水平居中的 DIV</div>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>垂直水平居中的 DIV</title>
<style type="text/css">
#pageFrame {
position: absolute; // 设置为绝对定位
left: 50%; // 设置显示坐标 X
top: 50%; // 设置显示坐标 Y
width:760px; // 设置 DIV 宽度
height:460px; // 设置 DIV 高度
margin-left:-380px; // 根据 DIV 的宽度,设置此值
background:#EEE;
}
</style>
</head>
<body>
<div id="pageFrame">垂直水平居中的 DIV</div>
</body>
</html>
转自:http://oneoo.com/articles/perfect-realization-of-the-level-of-intermediate-vertical-div.html