讓div相對於瀏覽器窗口居中。
方案一:純粹使用CSS實現
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>測試文件</title> <style> #test { /*准備一個長200px 寬200px的div,背景設置成黃色*/ width: 200px; height: 200px; background-color: #FC0; /*下面是核心代碼*/ margin: auto; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } </style> </head> <body> <div id="test"> </div> </body> </html>
上面這套方案是比較完美的方案,即便縮放瀏覽器窗口也能保證div居中。
方案二:利用Javascript實現
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>測試文件</title> <style> #test { width:200px; height:200px; background-color:#FC0; position:fixed; } </style> <script> window.onload = function(){ var screen_width = window.screen.availWidth; //獲取屏幕寬度 var screen_height = window.screen.availHeight; //獲取屏幕高度 var X = (screen_width - 200)/2; var Y = (screen_height - 200)/2; var div = document.getElementById("test"); div.style.left=X + "px"; div.style.top=Y + "px"; }; </script> </head> <body> <div id="test"></div> </body> </html>
幾個關鍵點說明下:
position:fixed 決定div是相對於瀏覽器窗口居中,而不是相對於一般意義上的父窗口居中。
必須使用window.onload保證在DOM加載完畢后才執行js,<script>標簽的defer屬性理論上也能實現此效果,但defer屬性只有IE瀏覽器支持,而且,我用了下,沒效果。