DIV在页面中垂直居中的方案
方案一:纯CSS
<!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" />
<meta name="author" content="Chomo" />
<link rel="start" href="http://www.14px.com" title="Home" />
<title>根据内容宽度、高度自适应,垂直水平居中,内容高度超过窗体时,垂直居顶</title>
<style type="text/css">
* { margin:0; padding:0; list-style:none; font-size:14px;}/*---该css reset仅用于demo,请自行换成适合您自己的css reset---*/
html { height:100%;}
body { height:100%; text-align:center;}
.centerDiv { display:inline-block; zoom:1; *display:inline; vertical-align:middle; text-align:left; width:200px; padding:10px; border:1px solid #f60; background:#fc0;}
.hiddenDiv { height:100%; overflow:hidden; display:inline-block; width:1px; overflow:hidden; margin-left:-1px; zoom:1; *display:inline; *margin-top:-1px; _margin-top:0; vertical-align:middle;}
</style>
</head>
<body>
<div class="centerDiv">
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
蓝色理想<br/>
</div><div class="hiddenDiv"></div>
</body>
</html>
方案二:有javascript参与
<!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>未知高度元素的垂直居中方法(JS)</title>
<script type="text/javascript">
function vMiddle(){
var middleDiv=document.getElementById("wrap");
var divHeight=middleDiv.offsetHeight;
var bodyHeight=document.body.offsetHeight ;
if(bodyHeight>divHeight)
middleDiv.style.marginTop=-divHeight/2+"px";
else{
middleDiv.style.marginTop=0;
middleDiv.style.top=0;
}
}
</script>
<style type="text/css">
html,body{height:100%;padding:0;margin:0;}
#wrap{width:800px;margin:0 auto;border:1px solid red;position:absolute;top:50%;left:50%;margin-left:-400px;}
</style>
</head>
<body onload="vMiddle();">
<div id=wrap>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
<a href=http://www.cssass.com/digg target=_blank>cssass的分享</a><br/>
</div>
</body>
</html>