<div class="codetitle"> <span><a style="CURSOR: pointer" data="42606" class="copybut" id="copybut42606" onclick="doCopy('code42606')"><u>复制代码</u></a></span> 代码如下:</div> <div class="codebody" id="code42606"> <br> <br> <br> <br><meta charset="utf-8"> <br><title>JS实现div居中</title> <br><style> <BR>/*外层div居中*/ <BR>#main { <BR>position: absolute; /*极为重要*/ <BR>background-color: blue; <BR>width:400px; <BR>height:200px; <BR>/*left:50%; <BR>top:50%; <BR>margin-left:-200px; <BR>margin-top:-100px;*/ <BR>border:1px solid #00F; <BR>} <br><br>#content { <BR>position: absolute; /*极为重要*/ <BR>background-color: yellow; <BR>width: 200px; <BR>height: 100px; <BR>/*left:50%; <BR>top:50%; <BR>margin-left:-100px; <BR>margin-top:-50px;*/ <br><br>/*div内部文字居中*/ <BR>text-align: center; <BR>line-height:100px; /*行间距和div宽度相同*/ <BR>} <BR></style> <br> <br><div id="main"> <br><div id="content"> <br>Sun <br> </div> <br> </div> <br><script type="text/javascript"> <BR>window.onload = function() { <BR>// 获取浏览器窗口 <BR>var windowScreen = document.documentElement; <BR>// 获取main的div元素 <BR>var main_div = document.getElementById("main"); <BR>// 通过窗口宽高和div宽高计算位置 <BR>var main_left = (windowScreen.clientWidth - main_div.clientWidth)/2 + "px"; <BR>var main_top = (windowScreen.clientHeight - main_div.clientHeight)/2 + "px"; <BR>// 位置赋值 <BR>main_div.style.left = main_left; <BR>main_div.style.top = main_top; <br><br>// 获取mcontent的div元素 <BR>var content_div = document.getElementById("content"); <BR>var content_left = (main_div.clientWidth - content_div.clientWidth)/2 + "px"; <BR>var content_top = (main_div.clientHeight - content_div.clientHeight)/2 + "px"; <BR>content_div.style.left = content_left; <BR>content_div.style.top = content_top; <br><br>} <BR></script> <br> <br> <br> </div>