CSS Random Background Image Rotation

Edit: If you do not have access to the PHP source code on your site, try this random background image script generator

Here's something I've been playing with lately to add a little bit of visual dynamic interest to sites that don't have frequently changing content. The concept is not new – use image rotation to display random images on each page load. No great problem there, simply use a server-side script to select a random image. But what if your images are not content, are purely presentational, and are (read 'should be') background images?

Using PHP to retrieve a random image from a folder, we can generate dynamic CSS declarations through the page headers. This means we can change background images randomly on page load, and we can control which images are available by adding or removing them from the images folder.

First up we need to create the PHP script that will get the images from a folder, select a single image at random, and write the CSS declaration to the page header. Everything you need is in the following scripts, and all that needs customising is the path to your style and image folders. Copy and save this file as dynamic_css.php.

<?php /*** Random Background Images

http://www.thought-after.com/2006/05/26/css-random-background-image-rotation/

This file will display a random background image to any element targetted through a CSS id.

1) Place this file in the same location as your sites main stylesheet file.

2) In the head section of each page place the following @import statement.

@import url(/path/to/dynamic_css.php)

NOTE: the import must occur after all other style sheet links, imports and declarations to avoid this dynamic style being over-written.

3) Create a folder to hold the images to be used for the random backgrounds.

4) Assign values to the following variables to complete the setup

$imgFolder : the path from the sites root to the image folder created at 3 above example:

$imgFolder = "/images/random-images/";

$element : the css ID of the element to apply the background image to example:

$element = "header";

5)    That's it!! ***/

// Set up
$imgFolder = "/images/random-images/"; // the path from the sites root to the image folder created at 3 above
$element = "header"; // the css ID of the element to apply the background image to

// That's it!! Nothing below this line needs to be changed
$img = null;

// build up the path to the image folder
if (substr($imgFolder,0,1) != '/') { $imgFolder = '/'.$imgFolder; }
if (substr($imgFolder,-1) != '/') { $imgFolder = $imgFolder.'/'; }
$path = $_SERVER['DOCUMENT_ROOT'] . $imgFolder;

// populate an array to hold valid file type extensions
$extList = array('gif','jpg','jpeg','png');

// create an array to hold the list of image files
$fileList = array();

// open a handle to the directory
$handle = opendir($path);

// loop through the contents of the directory
while ( false !== ( $file = readdir($handle) ) ) {
    // get the info for each file
    $file_info = pathinfo($file);
    // check that the file in in the allowed extensions array
    if ( in_array( strtolower( $file_info['extension'] ), $extList)    ) {
        // add the file to the array
        $fileList[] = $file; }
    }
    // close the handle to the directory
    closedir($handle);

    // if we have at least 1 file in the list
    if (count($fileList) > 0) {
        // select a random index from the file list array
        $imageNumber = time() % count($fileList);
       // assign the filename for that array index to the $img var
       $img = $imgFolder . $fileList[$imageNumber];

       $css = "#$element { background-image: url('".$img."'); }\n";

       // tell the browser what we're sending
       header('Content-type: text/css');
       // and write out the css
       echo $css;
    }
?>

Now in the head of our HTML page import the dynamic css:

<style type="text/css">@import url("/path/to/dynamic_css.php");</style>

If you have set up your path correctly, which I'll admit always catches me out, then each page load should see a random background image displayed in the element specified in the dynamic CSS.

Obviously this method can be extended and modified to suit you exact circumstances. I currently pass page identifiers through the import statement as part of a querystring which then query a database for specific content, meaning I can specify a range of images for use on each page, and on each element on that page. The possibilities are seemingly endless, and only limited by your imagination.

Edit (16/07/2007): I've tidied the script up a little to make it easier to implement. Just a couple of documented steps to follow, and thats' it!!

Share this:
  • Twitter
  • FriendFeed
  • Facebook
  • StumbleUpon
  • Digg
  • del.icio.us
  • LinkedIn
  • Google Bookmarks
  • Live
  • Reddit
  • Slashdot
  • Technorati
  • Tumblr

Tags: , , , ,

  1. Jason’s avatar

    Hi Scott,
    Just wanted to make sure you received my email.
    Jason

    Reply

  2. Jason’s avatar

    Scott…?
    Where'd you go?

    Reply

    1. Lafinboy’s avatar

      Hi Jason, been a hectic few days, sorry. I've replied via email.

      Reply

  3. Willis’s avatar

    If I wanted to use this script to add random backgrounds to more than one div, how would I do so without having to have multiply copies of your scripts to put the bg's in certain div's.

    Thanks,

    Reply

    1. Lafinboy’s avatar

      Hi Willis – you should be able to munge the $element variable value to achieve this. Assuming that you want to apply the background image to three elements with the ID's element1, element2 and element3, you could set the value to

      $element = "element1, #element2, #element3";

      Reply

      1. Willis’s avatar

        That would work but I'm wanting to pull a different image into each of 4 div from 4 different image folder so none of the divs will ever have the same background loaded at once.

        Reply

        1. Lafinboy’s avatar

          That would require quite a bit of surgery to this reasonably simple script.

          Reply

  4. Jehzeel Laurente’s avatar

    Thanks for sharing this! I think there's a shorter way to do this, but I just don't know how. Hmmm..

    Reply

    1. Faruk’s avatar

      <img src="/images/image.jpg" alt="OAVS Australia's cheapest domain names and web hosting plans" width="156" height="301" border="0" />

      Place your images in a folder 'images' and name your images image1.jpg, image2.jpg, image3.jpg etc.

      Make sure rand(1,3) reflects number of images in the folder.

      Reply

      1. Faruk’s avatar

        Ouch all my PHP code was stripted out. Here is I go again

        <img src="../graphics/homepage/image.jpg" alt="Australia's cheapest domain names and web hosting plans" width="156" height="301" border="0" />

        Please take the extra spaces out

        Reply

        1. Faruk’s avatar

          Gosh again!

          Hope this worked

          Reply

  5. Terry’s avatar

    Hi,
    Firstly I must say how good the free script is that is generated… works a treat!

    I found your free script after searching the internet for 2 days solid and trying various others.

    The thing is I have been looking for a script that does what yours does but changes the background image every few seconds and not on page load or refresh.

    I'm on my third day now looking at codes; CSS, Javascript, php, html you name it, chopping bits out of one and trying them in another but still can't achieve the desired effect.

    It's seems simple enough to do for foreground images and there are plenty of options to choose from on the internet, but nothing for background images!!!

    I have a quick search facility on my proto-type web which contains a couple of drop-down menus and a min/max amount input box.

    I want to have a background image behind this which rotates between several images but can't for the life of me achieve it.

    I need to call the script that does it from within a <td tag. for example <td id="whatever"

    or <td width="700" height="400" background-img: url="a php file with rotating images in

    If this is possible?

    Is there any chance you could adapt the script which is generated free to rotate images every few seconds or an amount of time chosen?

    I think if you can you will boost traffic to this site 10 fold as I have come across hundreds of other wanting to achieve the same thing while I have been searching.

    Pleaaaaaaaaaaaasssssssssssssssseeeeeeeeeeeeeeeeee

    Reply

  6. Arturo’s avatar

    Hello All,

    Well, I found this PostNuke-Zikula CMS and I would love to have my background image changing, at every time the page refresh or by after some time. But, I can not find any .HTML file to add the code, and as you will see, I am clueless on this programming and code stuff.

    The only thing I found on the Zikula folders, is a file where the background image is loaded is named Style.css and the line say:
    body {
    .
    .
    .

    background-image: url(../images/background.jpg);

    .
    .
    . etc.

    So, Can any one help me with this?

    Thanks!

    Reply

  7. Long Yuan’s avatar

    Hi. I'm currently an IT student doing a school project.
    I've tried to implement your code into my website but somehow, I can't get it to work.
    Is it okay if you could spare some time to take a look at my coding?

    Reply

  8. Grant’s avatar

    Thanks for this! It's a great help. Just what I was looking for!

    Reply

  9. orange’s avatar

    hi, i hv been trying but it seems not working. not sure if i missed any step..
    can help me to look at this scripts?
    http://newfields.chameleon.com.my/randomtry/a.html

    Reply

  10. Niyaz’s avatar

    Great tutorial dude , very useful ..
    Thanks alot.

    Reply

  11. Hugh’s avatar

    I really want to use this in a Wordpress theme…which has it's own header.php file, so that's where I'm putting the @import code like this:

    @import url(dynamic_css.php);

    I can't get it to work, and it may be because I don't understand paths very well….I've no idea where the root of my site is, especially as I'm testing this on a MAMP localhost installation, not online. The URL of my (local) site is:

    http://localhost:8888/wordpress/

    but if you followed the file structure to dynamic_css.php, it would be something like this:

    /htdocs/wordpress/wp-content/themes/snowblind/

    So I've no idea what the path 'from the site's root to the image folder' is!

    Any help appreciated.

    Hugh

    Reply

    1. Trevor’s avatar

      I'm also trying to use it in my Wordpress theme, which also has it's own header.php. I feel I did everything as directed above, and I even tried customizing it a bit, but nothing seems to work.

      Does anyone know how to get this, or any other random background image generator to work with Wordpress. I can't seem to find anything.

      -Trevor

      Reply

    2. Hugh’s avatar

      As Pink Floyd said……"Is there anybody out there?"…….

      ???

      Reply

  12. ChrisR’s avatar

    Hello,

    Hopefully someone can help me. I'm trying to use this script to rotate the overall site background. I've tried everything I can think of to get this to work. Could my problems be related to the fact that the body section of the CSS file doesn't start with a # (as seen below)?

    BODY {
    background: #012d4a;
    background-image: url(img/background3.png);
    background-position: top center;
    background-repeat: no-repeat;
    background-attachment:fixed;
    font-size: 1em;
    font-family: verdana;
    margin: 0;
    }

    This is the background image that I am trying to rotate… is it possible? Any help would be greatly appreciated!

    Thanks

    Chris

    Reply

    1. Lafinboy’s avatar

      Hi Chris, the script attaches itself to an element identified by an id attribute. Quick fix is to add an id attribute to your body element, and use this id in the script.

      Reply

      1. ChrisR’s avatar

        Hello and thanks for the quick reply! Just so I'm clear on your instructions, you're suggesting I make up an ID for this script, lets say we call it rotate. I would then do something like in my pages?

        Would I need to have the #rotate id added to my css file as well?

        I'm very new to css and php, sorry :P

        Reply

        1. ChrisR’s avatar

          I'm going to be "that guy", and reply to my own post… So, im my css file, I left the body section empty

          Body { }

          I then added a rotate id

          #rotate {
          background: #012d4a;
          background-position: top center;
          background-repeat: no-repeat;
          background-attachment:fixed;
          font-size: 1em;
          font-family: verdana;
          margin: 0;
          }

          From there, I did as you suggested, and put the id in my body tag . Everything worked, except this script. The background colour was correct, so I am assuming the rotate properties are applied to the body. However, I end up with no images.

          I have dynamic_css.php located in the same directory as my css file, though I'm not sure how it knows the name of the css file? Fortunately, I only have one css file so i guess that shouldn't be an issue. I put the following in the dynamic_css file;

          $imgFolder = "/img/rotate/"; (I also tried img/rotate/)
          $element = "rotate";

          My image directory contains two images, both .png files.

          I can't think of any other useful information :)

          Not sure where I could be going wrong?

          Cheers,

          Chris

          Reply

          1. Lafinboy’s avatar

            Hey Chris, have you included the @import style directive in the head of your page? It looks like you're doing everything else right. Do you have a URL I can have a look at so I can help debug?

  13. ChrisR’s avatar

    Hello,

    Yup, I have the @import directive in place. If you'd be willing to check it out, that would be great. My site is http://hasslefreegaming.com/v2/index.php. I'm new to css and php, the site is a work in progress :)

    Thanks again!

    Reply

  14. ChrisR’s avatar

    Hello.

    I was able to accomplish the random background with a different method, it's not as dynamic as this one, I have to put the file names in an array. since I'll only have a couple images, that is fine.

    Thanks!

    Chris

    Reply

· 1 · ... · 5 · 6 · 7