2012-09-01 74 views
0

我想在屏幕中心(水平和垂直)打開一個div。爲什麼我的容器沒有進入中心

var documnetWidth = $(document).width(), 
    documentHeight = $(document).height(), 
    widgetFormHeight = widgetForm.height(), 
    widgetFormWidth = widgetForm.width(); 

widgetForm.css({ 
    top: documentHeight/2 - widgetFormHeight/2, 
    left: documnetWidth/2 - widgetFormWidth/2 
}); 

我的小部件水平居中但垂直需要一些偏移。

回答

2

試試這個:而不是

documentHeight = $(window).height(), 

documentHeight = $(document).height(), 

你有它的方式,你都拿到文檔的高度可能會大於或小於瀏覽器的高度。

然後允許文檔多遠當前滾動的:

top: documentHeight/2-widgetFormHeight/2 + $(document).scrollTop(), 

演示:http://jsfiddle.net/vULHL/

+0

$(窗口)不能解決它。 –

+0

如果確定,他可以嘗試固定位置,或者按照建議使用scrollTop。 – sabithpocker

+2

答案已更新,以便按照演示允許當前文檔的滾動狀態。或者'position:fixed'會按照sabithpocker的建議來做(我最初沒有想到,因爲我太習慣於支持某個必須在IE6中運行的應用程序)。 – nnnnnn

6

你可以做到這一點

定義大小的DIV和位置固定,像這樣的:

div { 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    width: 200px; 
    height: 100px; 
    margin: -100px 0 0 -50px; 
    z-index: 99; 
} 

或者,如果你不想把它absolutl ÿ定位,可以給它的寬度,並將其設置爲:

div { margin: 0 auto; } 
+0

你的解決方案需要固定定位,如果你使用絕對定位,你應該考慮scrollTop也檢查@nnnnnn回答 – sabithpocker

+0

我已經更新了我的答案 – rahul

+0

+1爲純CSS解決方案 – sabithpocker

相關問題