I am creating a web page which currently looks like the following image:

What I am trying to do now, is replace the grass image with two or more alternating background images. These images must be repeating in the x direction. Example:

The gray background and the gradient between the grass and the gray background can be ignored.
All background images are 260x650 pixels in size and the number of images is static.
What I have tried, is creating a background like this:
background: url('bg1.png') 0 0 no-repeat, url('bg1.png') 260px 0 no-repeat
The problem is I cannot set repeat-x, because there has to be a margin of 260px between the images. This answer to other question states there is no such margin.
I would prefer not to combine the images in a single image.
My resources are plain JavaScript, CSS and HTML. My target browsers are relatively new(IE 9, but preferrably 8), so don't worry about old quirks.
See demo here.
Here's a function you can use:
function changeBodyBackground() {
var images = ['http://wardarthouse.com/stephanie_ward_gallery/water_colour/images/Color_Clouded_Sunburst.jpg', 'http://stmedia.startribune.com/images/260*650/1wcturbine0715.jpg',
'https://www.oki-ig.com/resources/doors/71-D_NTCPW_l.jpg']
var imagesWidth = 260;
var screenWidthToCover = 3000; // the max resolution expected
var i = 1, backgroundStyle = 'url("'+images[0]+'") 0 0 no-repeat';
while (i*imagesWidth < screenWidthToCover) {
backgroundStyle += ', url("'+images[i%images.length]+'") '
+(imagesWidth*i)+'px 0 no-repeat';
i++;
}
document.body.style.background = backgroundStyle;
}
Edit the images array with the URL of the images you need. They will be placed side-by-side with the order given in the array. Also, the spacing between the images is defined by the imagesWidth variable.
In the demo the background is being set when the button is clicked. You can, of course, call the function at the <head>, if you want the background images to be loaded right away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With