Keep body background image aligned with content
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.