2012-11-29 63 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/ –