Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacing between alternating background images

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

enter image description here

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:

bg repeating

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.

like image 840
Aart Stuurman Avatar asked Feb 20 '26 07:02

Aart Stuurman


1 Answers

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.

like image 166
acdcjunior Avatar answered Feb 22 '26 22:02

acdcjunior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!