Created
June 29, 2013 17:33
-
-
Save nicluo/5891978 to your computer and use it in GitHub Desktop.
Center and Scale background image using JQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.bgimgs{ | |
position:absolute; | |
top:0; | |
left:0; | |
z-index:-1000; | |
overflow:hidden; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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