2012-11-29 61 views
1

我有以下代碼:中心響應DIV

更新:

http://jsfiddle.net/Zdevq/2/

.container { 
    height: 100%; 
    width: 100%; 
    background: #eee; 
    position: absolute; 

} 

.box { 
    height: 100px; 
    width: 100px; 
    background: #222; 
    position: absolute; 

    /*Centering Method 2*/ 
    margin: -50px 0 0 -50px; 
    left: 50%; 
    top: 50%; 
} 

來自:http://designshack.net/articles/css/how-to-center-anything-with-css/

==但我想是模態框有一個相對於響應容器div的寬度。

有什麼辦法可以在響應div中製作真正響應的模態盒?

回答

3

你沒有正確的方式使用它,該功能必須在使用最新的jQuery進行文檔準備時初始化。

http://jsfiddle.net/n29up/1/

這是jQuery代碼 - 使用jQuery的是這樣的:

但一定要添加最新的jQuery插件

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js' type='text/javascript'></script> 

<script type='text/javascript'> 
    $(function(){ 

    $.fn.center = function() { 
     this.css("position","absolute"); 
     this.css("top", ($(window).height() - this.height())/2 + "px"); 
     this.css("left", ($(window).width() - this.width())/2 + "px"); 
     return this; 
    } 

    $(".box").center(); // on page load div will be entered            

    $(window).resize(function(){ // whatever the screen size this 
     $(".box").center();  // this will make it center when 
    });       // window resize happens 

    }); 
</script> 

你的小updated css

.container { 
    height: 100%; 
    width: 100%; 
    background: #eee; 
    position: absolute; 
} 

.box { 
    height: auto; 
    width: 70%; 
    background: gray; 
    position: absolute; 
    margin: 0; 
    left:0; 
    top:0; 
} 
+0

同樣的問題在這裏:如果箱子有或多或少的內容會怎麼樣: http://jsfiddle.net/Zdevq/7/ 我之前也試過這個,但它不是大小獨立的,例如,不會自動對齊垂直中心。 –

+0

然後我建議你使用jquery來居中div,那會非常好。 – Jai

+0

不知道該怎麼做。在調整窗口大小時,也不會有點「不平坦」嗎? –

0

這個

Check Fiddle

如何刪除從包裝盒中margin並添加min-heightmax-height的容器..

.container { 
    height: 100%; 
    width: 100%; 
    background: #eee; 
    position: absolute; 
} 

.box { 
    height: auto; 
    width: 70%; 
    background: gray; 
    position: absolute; 
    /*Centering Method 2*/ 
    left: 15%; 
    top: 45%; 
}​ 
+0

sry,我忘了設置容器來接管整個頁面的例子,它應該更像這樣:http://jsfiddle.net/Zdevq/2/ –

+0

檢查更新後的帖子.. –

+0

不幸的是這不會是大小獨立的,因爲當Box有更多的內容時,它不再是垂直居中: http://jsfiddle.net/Zdevq/6/ –