August 30th, 2010 by

A client asked me to implement function that allows to change background image randomly after each refresh. After some time of messing with rotation scripts I decided to create something myself. Here is my solution.

The first we have to prepare CSS. We will use an image with fixed position and 100% width and height.

html,
body { height: 100%; }

img#bg {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
}

And this code implements image into the HTML code. Put the code right after

<body>
<?php $random_image = rand(1, 5); /*let's choose random image...*/ ?>
<img id="bg" alt="" src="<?php bloginfo('stylesheet_directory');?>/images/<?php echo $random_image; ?>.jpg" />

Do not forget to name images you want to use for background like 1.jpg, 2.jpg, 3.jpg etc.

3 Responses to “Display random background on each page load”

  1. Jonathon says:

    Hi there, how would you code the CSS such that the random image is tiled accross the background?

    Thanks!

  2. Tia says:

    Where do you change the name of the images?? here?

    rand(1, 5)

    as in

    rand(/imgs/243.jpg, /imgs/285.jpg)

    Is that right? If so, this doesn’t work for me. :( I’m using WordPress, dropped this in the stylesheet:

    img#bg {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;}

    and I dropped the other code behind

    <body >

    as

    <img id="bg" alt="" src="/images/.jpg” />

  3. Tia says:

    oops…forgot code snippet wrapper.

    &lt;body &lt;?php body_class(); ?&gt;&gt;
    
    &lt;?php $random_image = rand(/imgs/243.jpg, /imgs/285.jpg); /*let's choose random image...*/ ?&gt;
    &lt;img id=&quot;bg&quot; alt=&quot;&quot; src=&quot;&lt;?php bloginfo('stylesheet_directory');?&gt;/images/&lt;?php echo $random_image; ?&gt;.jpg&quot; /&gt;
    

Leave a Reply