Skip to content

Instantly share code, notes, and snippets.

@apathetic
Created May 7, 2010 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apathetic/9933205b335e0a0b3337 to your computer and use it in GitHub Desktop.
Save apathetic/9933205b335e0a0b3337 to your computer and use it in GitHub Desktop.
resize background image to fit
function resizebg() {
if ($('#backstretch')) {
var w, h, x, y;
var iw = $('#backstretch').width();
var ih = $('#backstretch').height();
var winx = $(window).width();
var winy = $(window).height();
var constrain = winx/winy > iw/ih ? 'w' : 'h';
if(constrain=='w') {
w = winx;
h = winx * ih / iw;
x = 0;
y = -(h - winy) / 2;
} else if(constrain=='h') {
w = winy * iw/ih;
h = winy;
x = -(w - winx)/2;
y = 0;
}
$('#backstretch').css({
width: w+'px',
height: h+'px',
top: y+'px',
left: x+'px'
});
}
}
$(window).load(function() { resizebg(); });
$(window).resize(function() { resizebg(); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment