using an image as a site background

Here is a demo of a page with a background image that resizes and sets the left and top margins based on screen size.

Here is the code needed for the image to maintain the normal aspect ratio
Built using jQuery:
$(function(){
///// storing the screen width and height /////
var wHeight = $(window).height();
var wWidth = $(window).width();

//// initial function to set the image height, width, top and left margins (for centering) /////
function imageSize(){
if(wWidth > wHeight){

$(‘#main-image’).width(wWidth).height(wWidth);

}

else if(wWidth < wHeight){

$(‘#main-image’).width(wHeight).height(wHeight);

}

else{

$(‘#main-image’).width(wWidth).height(wHeight);

}

var imLeft = $(‘#main-image’).width()/2;
var imTop = $(‘#main-image’).height()/2;
$(‘#main-image’).css({‘margin-left’:-imLeft, ‘margin-top’:-imTop});

};

/////////  calling the function on load ///
imageSize();

//// changing the image size and margins when the browser is resized ////

$(window).resize(function(){

var wHeight = $(window).height();

var wWidth = $(window).width();

if(wWidth > wHeight){
$(‘#main-image’).width(wWidth).height(wWidth);

}
else if(wWidth < wHeight){
$(‘#main-image’).width(wHeight).height(wHeight);

}
else{
$(‘#main-image’).width(wWidth).height(wHeight);

}
var imLeft = $(‘#main-image’).width()/2;
var imTop = $(‘#main-image’).height()/2;
$(‘#main-image’).css({‘margin-left’:-imLeft, ‘margin-top’:-imTop});

});

});

Comments are closed.