2009-12-07 70 views
-2

如何在具有位置的任何分辨率下以精確的屏幕中心調整div:絕對。調整div位置

+0

中心屏幕?或瀏覽器窗口的中心? – peirix 2009-12-07 13:08:46

回答

4

如果div有一個已知的寬度和高度,你可以使用負保證金:

div { 
    position: absolute; 
    width: 800px; 
    height: 500px; 
    left: 50%; 
    top: 50%; 
    margin-top: -250px; 
    margin-left: -400px; 
} 

通知負利潤的寬度和高度的一半。

如果div的大小不知道或流體,你必須使用JavaScript。以下是如何使用jQuery進行工作:

$(function() { 
    $(window).resize(function() { 
     $('div.something').css({ 
      left: $(window).width() - ($(this).width()/2), 
      top: $(window).height() - ($(this).height()/2) 
     }); 
    }); 
    $(window).resize(); 
}); 
+0

請注意,這將(在小窗口中)將內容放置在窗口之外而不使其可用滾動條訪問。 – Quentin 2009-12-07 12:53:18

1

以下幾段腳本將爲您提供窗口中可視空間的高度和寬度。

<script type="text/javascript"> 
     <!-- 
      function pageWidth() { 
       return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null; 
      } 
      function pageHeight() { 
       return window.innerHeight != null ? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null; 
      } 
      function posLeft() { 
       return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0; 
      } 
      function posTop() { 
       return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0; 
      } 
      function posRight() { 
       return posLeft() + pageWidth(); 
      } function posBottom() { 
       return posTop() + pageHeight(); 
      } 

      pageWidth() 
      pageHeight() 
     //--> 
    </script> 

簡單的數學的一點點就會讓你的屏幕的中心x =寬度/ 2 Y =身高/ 2

設置頂部位置爲y +的xy座標(DivHeight/2),潛水的左側位置X-(DivWidth/2)

0

CSS Dead Center

selector { 
    position: absolute; 
    width: 100px; 
    height: 100px; 
    top: 50%; 
    left: 50%; 
    margin-top: -50px; 
    margin-left: -50px; 
} 
+0

基本上和Tatu的答案完全相同......你可以用這個答案代替嗎? – peirix 2009-12-07 13:28:58

+0

我以爲我會鏈接'CSS Dead center'文章。 – 3zzy 2009-12-07 16:38:03