Skip to content

Instantly share code, notes, and snippets.

@nicluo
Created June 29, 2013 17:33
Show Gist options
  • Save nicluo/5891978 to your computer and use it in GitHub Desktop.
Save nicluo/5891978 to your computer and use it in GitHub Desktop.
Center and Scale background image using JQuery
.bgimgs{
position:absolute;
top:0;
left:0;
z-index:-1000;
overflow:hidden;
}
$(document).ready(function() {
//Initial load and size
$("body").prepend('<div class="bgimgs" id="bgimgs"><div id="bgimg1" class="bgimg"><img src="img/bg.jpg"></div></div>');
resizeBgDiv();
});
$(window).on('resize', function(event){
resizeBgDiv();
});
var resizeBgDiv = function(){
//Input background height, width here
var bgh = 2560;
var bgw = 1920;
var height = window.innerHeight;
var width = window.innerWidth;
var hratio = height/bgh;
var wratio = width/bgw;
if(hratio < wratio){
//negative margin up
var hexpect = wratio * bgh;
var hdiff = (hexpect - height)*0.5;
$('#bgimgs').css({
'margin-top': -hdiff,
'margin-left': 0,
'width': width,
'height':hdiff+height});
$('.bgimg').css({
'width':width,
'height':hexpect});
$('.bgimg').children().css({
'width':width,
'height':hexpect});
} else {
//negative margin left
var wexpect = hratio * bgw;
var wdiff = (wexpect - width)/2;
$('#bgimgs').css({
'margin-top': 0,
'margin-left': -wdiff,
'width': width+wdiff,
'height' : height});
$('.bgimg').css({
'width':wexpect,
'height':height});
$('.bgimg').children().css({
'width':wexpect,
'height':height});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment