How to make background image scale the full page (Non CSS3)


#1

I’ve see an example at http://css-tricks.com/perfect-full-pa… of a jQuery method that should work but I’m having trouble implementing it. Is this even possible or am I wasting my time?

Here is some of their sample code:

jQuery Method

This whole idea becomes a lot easier (from a CSS perspective) if we know if the aspect ratio of the image (inline we intend to use as a background) is larger or smaller than the current aspect ratio of the browser window. If it is lower, than we can set only the width to 100% on the image and know it will fill both height and width. If it is higher, we can set only the height to 100% and know that it will fill both the height and width.

We have access to this information through JavaScript. As usual around here, I like to lean on jQuery.


#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

$(window).load(function() {

var theWindow = $(window),
bg = ("#bg"),
aspectRatio = $bg.width() / $bg.height();

function resizeBg() {

if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass(‘bgheight’);
} else {
$bg
.removeClass()
.addClass(‘bgwidth’);
}

}

theWindow.resize(function() {
resizeBg();
}).trigger(“resize”);

});

This doesn’t account for centering, but you could definitely alter this to do that. Credits to Koen Haarbosch for the concept behind this idea.

Works in:

IE7+ (could probably get in IE6 with a fixed position shim)
Most any other desktop browser


#2

Hey Chris, were you ever able to get this to work? Or did you have to pursue a new solution?


#3

Hey Chris, were you ever able to get this to work? Or did you have to pursue a new solution?


#4

Hi Jimmy - back when Chris originally asked this jQuery was an alternative because browser support for css3 (and the background-image property in particular) wasn’t as widespread as it is now. Now, almost everyone who comes across your page will be using a browser that supports the background-image property, so that shouldn’t be a major issue.

Was there a particular reason you were looking for a jQuery alternative?