你沒有正確的方式使用它,該功能必須在使用最新的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
不知道該怎麼做。在調整窗口大小時,也不會有點「不平坦」嗎? –