简体   繁体   中英

Jquery/CSS: Full size background image

I am currently working with a jquery plugin for setting my background image. The issue i am having is with the CSS/JQuery making the page in-proportionate. My content lies inside the #container div so I have set its position to absolute(originally was relative). How can I have the content of the page be aligned in the center and keep the properties of a 100% height? EXAMPLE

This is before the jquery plugin- CSS 100% height- EXAMPLE

Jquery Background plugin

<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 related to the issue

#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 to call function

<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>

This centers it -

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

it's kind of hacky, but it works.

50% shift (to keep it centered based on width)

half of width, plus border = 478.5 (or 488) to keep it centered in frame. And of course, with "left" only works because it's got position: relative; attached to it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM