<html>
<head>
<style>
body{ TEXT-ALIGN: center; }
#center{ MARGIN-RIGHT: auto;
MARGIN-LEFT: auto;
height:200px;
background:#F00;
width:400px;
vertical-align:middle;
line-height:200px;
}
</style>
</head>
<body>
<div id="center"><p>test content</p></div>
</body>
</html>
说明:
vertical-align:middle;表示行内垂直居中,我们将行距增加到和整个DIV一样高line-height:200px;然后插入文字,就垂直居中了。
CSS+DIV控制页面中元素垂直居中代码 全局和区域垂直居中
<style type="text/css" media=screen>
body
{
text-align: center;
}
#a
{
width: 200px;
height: 400px;
background: #000;
}
#b
{
margin-top: expression_r((a.clientHeight-50)/2);
width: 50px;
height: 50px;
background: #FFF;
}
#c
{
position: absolute;
left: expression_r((body.clientWidth-50)/2);
top: expression_r((body.clientHeight-50)/2);
width: 50px;
height: 50px;
background: #F00;
}
</style>
<div id="a">
<div id="b"></div>
</div>
<div id="c"></div>
另一方法:
<div style="background:blue;position:absolute;left:expression_r((body.clientWidth-50)/2);top:expression_r((body.clientHeight-50)/2);width:50;height:50"></div>
***************************************
二,用JS使层居中
把如下代码加入<body>区域中
<DIV id=L1 style="HEIGHT: 107px; LEFT: 341px; POSITION: absolute; TOP: 585px; WIDTH: 205px; Z-INDEX: 1">
<TABLE bgColor=#ffffff border=1 borderColorDark=#ffffff borderColorLight=#000000 cellPadding=0 cellSpacing=0 width="100%">
<TR>
<TD height=1 width=178>□::BEST4U论坛::</TD>
<TD align=middle οnclick="L1.style.visibility='hidden'"
style="CURSOR: hand" width=21>х</TD></TR>
<TR vAlign=top>
<TD colSpan=2
height=91>欢迎光临本站!<BR><BR>本站域名:<BR>http://webform.cn
</TD></TR></TABLE></DIV>
<SCRIPT LANGUAGE="JavaScript">
function moveit() //这个函数用于把层放到浏览器中间
{
L1.style.left=((document.body.offsetWidth-parseFloat (L1.style.width))/2)+document.body.scrollLeft;
L1.style.top=((document.body.offsetHeight-parseFloat (L1.style.height))/2)+document.body.scrollTop;
}
window.οnlοad=moveit; //网面打开时时执行moveit()
window.οnresize=moveit; //当调整浏览器大小时执行moveit()
window.οnscrοll=moveit; //当拉动滚动条时执行moveit()
</SCRIPT>