SiteKickr Web Development

Background Image – Stretched and Constrained Proportions

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

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');