第一种:全CSS控制,层漂浮(适用于做登陆页面)
代码如下:
<mce:style type="text/css" title="currentStyle" media="screen"><!--
#divcenter{
position:absolute;/*层漂浮*/
top:50%;
left:50%;
width:300px;
height:300px;
margin-top:-150px;/*注意这里必须是DIV高度的一半*/
margin-left:-150px;/*这里是DIV宽度的一半*/
background:yellow;
border:1px solid red;
}
--></mce:style><style type="text/css" title="currentStyle" media="screen" mce_bogus="1">#divcenter{
position:absolute;/*层漂浮*/
top:50%;
left:50%;
width:300px;
height:300px;
margin-top:-150px;/*注意这里必须是DIV高度的一半*/
margin-left:-150px;/*这里是DIV宽度的一半*/
background:yellow;
border:1px solid red;
}</style>
</head>
<body>
<div id="divcenter">
this is a test
</div>
</body>
</html>
第二种:JS + CSS控制,不漂浮(适用于做登陆页面)
代码如下:
<body style="height:100%; width:100%; text-align:center;" onload=cen()>
<div id = "testdiv" name="testdiv" style="margin:0 auto; border:1px solid red; height:400px; width:400px;">
DIV居中演示
</body>
</html>
最简单适用的一种 上下左右都居中,兼容所有浏览器
<div style="position:absolute; top:50%; height:240px;border:1px solid red; margin:0 auto; margin-top:-120px; width:300px; left:50%; margin-left:-150px;"></div>