2009-12-07 5 views

ответ

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

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> 

Немного простой математики получит вам ху координаты центра экрана х = Ширина/2 у = Высота/2

установить верхнюю позицию у + (DivHeight/2), а левое положение погружения в х- (DivWidth/2)

0

CSS Dead Center

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

Это в основном тот же самый ответ, что и у Тату ... Вы могли бы просто поддержать этот ответ? – peirix

+0

Я думал, что свяжусь с темой «CSS Dead Center». – 3zzy

Смежные вопросы