1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>JS实现div居中</title> 6 <style> 7 /*外层div居中*/ 8 #main { 9 position: absolute; /*极为重要*/ 10 background-color: blue; 11 width:400px; 12 height:200px; 13 /*left:50%; 14 top:50%; 15 margin-left:-200px; 16 margin-top:-100px;*/ 17 border:1px solid #00F; 18 } 19 20 #content { 21 position: absolute; /*极为重要*/ 22 background-color: yellow; 23 width: 200px; 24 height: 100px; 25 /*left:50%; 26 top:50%; 27 margin-left:-100px; 28 margin-top:-50px;*/ 29 30 /*div内部文字居中*/ 31 text-align: center; 32 line-height:100px; /*行间距和div宽度相同*/ 33 } 34 </style> 35 <body> 36 <div id="main"> 37 <div id="content"> 38 Sun 39 </div> 40 </div> 41 <script type="text/javascript"> 42 window.onload = function() { 43 // 获取浏览器窗口 44 var windowScreen = document.documentElement; 45 // 获取main的div元素 46 var main_div = document.getElementById("main"); 47 // 通过窗口宽高和div宽高计算位置 48 var main_left = (windowScreen.clientWidth - main_div.clientWidth)/2 + "px"; 49 var main_top = (windowScreen.clientHeight - main_div.clientHeight)/2 + "px"; 50 // 位置赋值 51 main_div.style.left = main_left; 52 main_div.style.top = main_top; 53 54 // 获取mcontent的div元素 55 var content_div = document.getElementById("content"); 56 var content_left = (main_div.clientWidth - content_div.clientWidth)/2 + "px"; 57 var content_top = (main_div.clientHeight - content_div.clientHeight)/2 + "px"; 58 content_div.style.left = content_left; 59 content_div.style.top = content_top; 60 61 } 62 </script> 63 </body> 64 </html>