This morning, we set about finding a way to stretch a site background image with the following requirements:

  • The background must fill the height and width of the browser viewing window
  • The background must maintain it's size proportions
  • It must work in browsers that don't yet support CSS 3

The following snippets illustrate our solution:

The HTML

...
<body>
  <div id="page-background">
    <img src="/src/img/bg.jpg" width="100%" height="100%" alt="" />
  </div>
  <div id="document">
...

The CSS

html,body { height: 100%; margin: 0; padding: 0; }
#page-background { position: fixed; bottom: 0;
    left: 0; width: 100%; height: 100%; }
#document { position: relative; z-index: 1; }

The JavaScript / jQuery

resizeBG = function() {
    var image = $('#page-background img');
    image.removeAttr("width");
    image.removeAttr("height");
    var imageWidth = image.attr('width') || image.width();
    var imageHeight = image.attr('height') || image.height();
    var ratio = imageHeight / imageWidth;
   
    var h = $(window).height();
    var w = $(window).width();
   
    $('#page-background img, #page-background').css('width', w);
    $('#page-background img, #page-background').css('height', w * ratio);
}

$(window).load( resizeBG );
$(window).resize( resizeBG );

 

If you have a higher res background image, you may notice some "jumpiness" when the page first loads, as the image is resized in front of the viewer's eyes.

To avoid this, we can hide the image until the resizing is complete.

Add the following CSS:

#page-background { visibility: hidden; }

And, the following jQuery to the end of your resizeBG function:

$('#page-background').css('visibility', 'visible');

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *