2012-08-03 125 views
3

我目前正在使用jquery插件來設置我的背景圖片。我遇到的問題是CSS/JQuery使頁面不成比例。我的內容位於#container div內,因此我將其位置設置爲絕對(原來是相對的)。我怎樣才能讓頁面的內容在中心對齊並保持100%的高度屬性? EXAMPLEJquery/CSS:全尺寸背景圖片

這與之前的jQuery plugin- CSS 100%高度 - EXAMPLE

jQuery的背景插件

<script> 
(function($) { 
    $.fn.fullBg = function(){ 
    var bgImg = $(this);   

    function resizeImg() { 
     var imgwidth = bgImg.width(); 
     var imgheight = bgImg.height(); 

     var winwidth = $(window).width(); 
     var winheight = $(window).height(); 

     var widthratio = winwidth/imgwidth; 
     var heightratio = winheight/imgheight; 

     var widthdiff = heightratio * imgwidth; 
     var heightdiff = widthratio * imgheight; 

     if(heightdiff>winheight) { 
     bgImg.css({ 
      width: winwidth+'px', 
      height: heightdiff+'px' 
     }); 
     } else { 
     bgImg.css({ 
      width: widthdiff+'px', 
      height: winheight+'px' 
     });  
     } 
    } 
    resizeImg(); 
    $(window).resize(function() { 
     resizeImg(); 
    }); 
    }; 
})(jQuery) 
</script> 

CSS相關問題

#container { 
    position: relative; 
    margin: 0 auto; 
    width: 945px; 
    background: #f0f0f0; 
    height: auto!important; 
    height: 100%; 
    min-height: 100%; 
    border-right: 15px solid #000; 
    border-left: 15px solid #000; 
} 

.fullBg { 
    position: absolute; 
    top: 0; 
    left: 0; 
    overflow: hidden; 
} 

HTML/Inline JS調用函數在

<img src="images/raven_bg.jpg" alt="" id="background" /> 
<div id="container"> 
</div> 
<script> 
$(window).load(function() { 
    $("#background").fullBg(); 
});///this comes right before the closing body tag 
</script> 
+0

你有瀏覽器限制嗎?有什麼理由不能在CSS中使用背景大小? – 2012-08-03 21:16:02

回答

2

這中心它 -

#container { 
    margin-left: 50%; 
    left: -488px; 
} 

它是一種哈克,但它的作品。

50%的偏移(以保持其居中基於寬度)

半高寬,加上邊界= 478.5(或488)以保持其在幀的中心。當然,「左」只能起作用,因爲它有位置:相對;附加到它