<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> <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%; 🎜>top:50%; <BR>margin-left:-200px; <BR>margin-top:-100px;*/ <BR>border:1px solid #00F; <br>} <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%; >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>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.cliclientHeight)/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_divdivpHeight)/22" ; <br>content_div.style.left = content_left; <BR>content_div.style.top = content_top; <BR><BR>} <BR></script> </div>