Keep body background image aligned with content

This is probably not a very common issue, but here’s a nice trick to keep the background image of the body element aligned with the page content (instead of window border). You may want to obtain this effect, for example, when using a particular background image which you prefer to show near the border of your main wrapper. Being based on Javascript you should not use this method to provide core functionality to a web page.

If browser windows were not resizable this task could be easily resolved using CSS background-position property, but since the only non resizable windows are the mobile ones we have to find a way to dynamically adjust the background-position property to each user’s window size.

The below image represents a simplified use case of this method: I want to use the checkers background for header and body and keep them aligned.

By default it can easily be rendered like in the following image:

So what we need is function to calculate the proper background-position value to keep the two backgrounds aligned and apply it on document load and window resize events.

This is our code:

// the image width of your background
var patternWidth = 150;
// you will have to test a bit to find the proper value here (should be between 0 and patternWidth)
var myOffset = 0;
// get the distance between the left window border and the container
var leftEdgeToPageDistance = ($(window).width() - $('.container').width()) / 2;
// calculate the offset needed to keep the backgrounds in sync
var bgOffset = leftEdteToPageDistance % patternWidth;
// apply!
$('body').css('background-position', bgOffset - myOffset + 'px top');

As stated in comments, you’ll have to find the proper value of myOffset to match the header background.

Leave a Reply