你没有正确的方式使用它,该功能必须在使用最新的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;
}
来源
2012-11-29 18:32:37
Jai
同样的问题在这里:如果箱子有或多或少的内容会怎么样: http://jsfiddle.net/Zdevq/7/ 我之前也试过这个,但它不是大小独立的,例如,不会自动对齐垂直中心。 –
然后我建议你使用jquery来居中div,那会非常好。 – Jai
不知道该怎么做。在调整窗口大小时,也不会有点“不平坦”吗? –