I have a document where I use a 40×40 pixel repeated background texture on the body.
Then I have a div with a set width and height and centered with margin: 40px auto 0 auto;
Now, the background image of this div (let’s say it’s 960×500, same as the element itself) has the same texture as the body. I cannot use a transparent png, because of a graphical effect I’m trying to achieve with this image.
However, for the effect to work, the background of the div needs to be seamless with the texture of the body. The user should not even be able to tell that there is a separate block element there; just an endless sea of the texture, with a detail in the middle of it all.
This becomes difficult as the div is centered, and as such, its horizontal distance from the left varies.
How can I make sure that the background texture on the body always matches the simulated texture in the div to the pixel, regardless of page width?
I’m not scared to use a JS solution if necessary, but obviously would prefer a pure CSS solution.
What you want to do is to set the background image on the body element to start in the middle. So:
This means that no matter how the window is resized, you will have a predictable area within the repeating pattern.
You’ll then have to tailor the containing div’s background to make the tiling in the body.
Here is some code showing how this method would work: http://jsbin.com/olabos/2/edit. Note how resizing the window does not put the pattern out of sync. Hover over the middle of the preview to see where the wrapping div is.
NOTE: some caveats to this technique, depending on how the browser handles half a pixel, you will get a 1pixel difference in the background. I don’t know of another technique that will solve your problem, so hopefully you can live with being 1px off.