Journal

Easy Random CSS Backgrounds

31 May 2005 › 38 comments

Update: Since I no longer rotate the header images on this site, I have updated this tutorial. Also, I figured I should set up an example page to show how this CSS + PHP tutorial works. You can check out the demo here:

This article was prompted by a question asked on the Textpattern forum, regarding how to randomize CSS backgrounds. After googling around for a bit, and checking various forums for better solutions, I decided to just write up my own article on how I do it. Due to the simplicity of how this works, this will be a very brief explanation. I only say it’s simple because the tough part has already been done by Dan Benjamin.

  1. Go download rotator.txt from A List Apart.
  2. Put the images to be rotated in the same directory as rotator.php.
  3. Upload all the files via FTP.

Thus far, these instructions seem pretty typical for a rotator script, except we’re not going to reference it in our HTML, even though it is the typically suggested method of displaying a random image. We of course, want to separate presentational images (mere eye-candy) from content as much as possible, and are therefore going to make our images display in a CSS background. But wait, can we just reference a PHP file for our background image? Yes it really is that simple. Here is the example code:

XHTML:

<div id="rotator">&nbsp;</div>

CSS:

#rotator
{
  background: url(images/rotator.php) no-repeat center top;
  width: 700px;
  height: 150px;
}

The way that Dan has written this snippet of PHP is ingenious. It is a “smart” rotator file, meaning that no additional configuration is needed on your part. It will realize what images reside in the same directory and select one at random to display as your CSS background. Size your images consistently, so that you don’t have random gaps in your <div>.

Do not upload files such as Thumbs.db if you are on Windows, or .DS_Store if using a Mac. If these files are within the same directory as the rotator file, it will attempt to put them into rotation as background images. This will cause some funky behavior, so it is best to just leave them out.

The <div> can of course be named whatever, with any dimensions you want, and you can easily replace the non-breaking space with the name of your site or section. While there is nothing special about having random images on a site, there are several benefits for doing it this way…

  1. No alt corresponding attribute needed, since it’s not content.
  2. PHP based, so it works even when JavaScript is turned off.
  3. It’s very easy to maintain and can be used site-wide.

So there you have it, a really easy way of switching around background images, without having to mess with extra JavaScript or XML configuration files! You simply add or delete images from the directory you want the rotator script to draw from, and it does the rest. Just make sure to keep all the images for rotation in their own directory, so you don’t end up cycling through those meant for other purposes.

Note: special thanks to Jonathan Snook for his expert input.

Discussion + Dissension

  1. #1 Audry

    I haven’t tried it yet. But while reading your artilce I wondered if you had it enabled here and when I refreshed I saw it in action!

    However, I really liked the first image that appeared. Now I have to keep refreshing if I want to see it again!

    :)

    Thanks for the article—gonna go try it out.

    Audry

  2. #2 Nathan Smith

    I’m glad you found the article helpful!

    By the way, I have my header set to randomly display one of twenty-six possible images, so you might have to refresh quite a bit. :)

  3. #3 Ray

    Thanks for the how-to. I finally updated the “Picture of the Moment” on my site thanks to this handy little lesson. I was going in and manually changing the picture every time and it was getting neglected. The same picture would be up for over a month at times. But now I’ve got quite a few pictures in there that constantly change and, to me, keep it looking fresh. Thanks again.

  4. #4 Nathan Smith

    Ray, that’s exactly what my problem was. Also, I wanted to be able to use as few Textpattern templates as possible.

    So, I’ve got 3 templates right now, one for the main page, one for all the sub-pages, and one for the archive page. And they all stay looking nice and fresh thanks to Automatic Labs!

  5. #5 Ronald

    [Offtopic]
    Just a hint… The colors you’re using for links is almost the same as you use for your normal text. For a colorblind (like me), it is really impossible to see the links :(
    [/offtopic]

  6. #6 Nathan Smith

    Ronald, what color combination would work better for you?

  7. #7 Jamie

    Nice! Saw this in the forum. Have a site I can use this on right now, so perfect timing. You saved me some hunting!

  8. #8 Rusty

    Nice article! I may put it to use on some of my websites.

    In response to the link colour – I’m also colour-blind and am having the same problems as Ronald. You might find some insight on these pages:
    http://jfly.iam.u-tokyo.ac.jp/color/
    http://www.vischeck.com/vischeck/vischeckURL.php

    Cheers,
    Andrew

  9. #9 Chris

    Nice job. I hadn’t thought about doing a rotator that way.

  10. #10 Jonathan Sampson

    Nathan,

    Zdrustvutsye! Man, your site is looking awesome dude, and am increasingly envious of your insane skills :) Praise the Lord you are able to communicate your knowledge in an easy-to-follow way! Keep up the fantastic work, and when we stand before the Lord, we’ll bring our resumes and see if we can make www.heaven.com

    Jonathan

  11. #11 Ronald

    Nathan, this is perfect ;)

  12. #12 Nathan Smith

    Ronald, I’m glad that my site is more accessible now. I guess there is good reason that default links are blue for most browsers!

    I’m going to be giving a lecture during our summer web-design class about how to make things more accessible to color-blind people, now that I’ve been made aware of it. Thanks.

  13. #13 Susan

    Sometimes it comes up with no image… does anyone know why? I set it up exactly the way you say I should, except that within the header div I have an image to overlay on it. Anyone else have this problem?

  14. #14 Nathan Smith

    Susan: You might want to check if you’ve accidentally uploaded any hidden files with your images. This happens sometimes if you’re using OSX, as it writes additional data files to the directory, so if you’ve simply dragged and dropped the entire folder into an FTP transfer, all the files go up. The rotator.php file can see them, and attempts to put them into rotation, even though they aren’t themselves images. Prune those files, and check it again.

  15. #15 Charles Leo

    That script is awesome! Thaks for all your help it has saved me a tremendous time in research and I really appreciate it.

    One question – is there a way to easily convert this to a timed interval slideshow type or random generator?

  16. #16 Nathan Smith

    Charles: I think this is possible, but not the way I’ve done it. That method would involve using JavaScript instead of PHP. The benefit of this is that they self-rotate while the user is on the page. The drawback is that it’s based on client-side scripting, which means they won’t see it if JavaScript is disabled. For more on that method, go here…

    http://www.dyn-web.com/javascript/rotate-img/

  17. #17 Charlie Hazlett

    HEy, thanks for the script! I had this bright idea that I might be able to have a random banner using CSS, so I googled it, and found your script.

    It worked for me right out of the “box”, thanks, again.

  18. #18 Nathan Smith

    Craig: You’re welcome. Glad it works for you. Like you, I wondered to myself if this would be possible. Realizing that it’s not with JavaScript, I started to look around for server-side PHP solutions, and that’s when I happened upon the script from Automatic Labs. Gotta love the open-source community!

  19. #19 Scott

    Any ideas on how to attach a url to each of the images?

    I’m looking to have the background image of a list automatically rotate but also be linked.

  20. #20 Nathan Smith

    Scott: I think there are some instructions on how to do that, within the comments of the rotator.php file. It shows how you can specify which image displays by URL, so possibly that could be re-tooled to rotate remote images. Do you not have access to the directory containing your images? It would probably be easiest to just put the rotator file within that same directory.

  21. #21 Scott

    I guess I should have clarified. I’m trying to determine if you can attach links to the images. So when the rotator script pulls an image into the background of a div can you associate a link with each image that gets passed into the href that’s within the div? I’m not even sure if it’s possible.

  22. #22 Nathan Smith

    Scott: In this case, you’d need to use a JavaScript, because that pulls things into the foreground. CSS can only really be used effectively for backgrounds. So, it is doable, just not with this particular method.

  23. #23 Joe Blow

    Hi Nathan,

    I just found this tute, used the script and it works great.

    One thing…. I found I had the same problem as Susan did earlier with the blank pics. Turns out that if you are on a *nix box and don’t chown the pics to the correct ownership the pic won’t display.

    but that is easy fixed.

    Thanks again.

  24. #24 Nathan Smith

    Ah, that’s a good tip, thanks! Yeah, the script can act a little quirky sometimes. I think, because it’s meant to be versatile, it needs specifically only images within its folder, otherwise it attempts to rotate everything. I hadn’t heard about the file ownership issue, so that’s good to know.

  25. #25 Joel

    Dude. That is completely the most awesome thing I’ve seen on the web in a long time. So simple!! Who knew image rotation could be so satisfying. Forget jscript. This is fantastic.

  26. #26 Nathan Smith

    Joel: Thanks, glad you found it helpful! I just wish that I would’ve written the PHP rotator, and thought of it a long time ago! That’s what is great about open source, a lot of collaborative effort, and people reusing things in new and inventive ways.

  27. #27 Richard Anderson

    this post is cooking with rocketsauce, I’ve been looking for a good php based random image rotator. Cant wait to try it out!

  28. #28 Nathan Smith

    Richard: Yeah, I was searching for a solution like this myself, so when I happened upon the script from Automatic Labs, it was a God-send. I’m going to set up a demo page for this technique, as I don’t make use of it in my actual site design any longer. Google still brings quite a few people here though, so I figure it will be good to show an example.

  29. #29 Noobie

    Help! I am not exactly sure what the problem is, but I only have a blank background. I am new to both PHP & CSS and am using Dreamweaver. I’m trying to change the page background, not a table background if that makes any difference. Any help will be appreciated

  30. #30 Nathan Smith

    This method can’t be implimented just in a desktop environment. It needs to be done on a web server with PHP installed, or on a local computer with WAMP running. Without seeing your actual site, I can’t offer more advice than that.

  31. #31 Noobie

    Thanks Nathan, I checked my server, and they support PHP up to version 5. I am also downloading WAMP to test it out locally. Thanks Nathan, I appreciate your help.

  32. #32 Noobie

    I got the random background to work, looks great! BTW if anyone could tell me how randomize flash movies I would greatly appreciate it

  33. #33 Nathan Smith

    For that, check out Kirupa.com. He’s got tons of Flash experiments and examples. I think this might be what you’re looking for:

    kirupa.com/developer/actionscript/loading_random_movie.htm

  34. #34 Noobie

    thanks again Nathan

  35. #35 NeillM

    Great, excellent little tool, anyone any idea as how to set the image swap on a time basis rather than reloading the page, i know it can be done in Javascript, but want to stay away from client side scripting.

  36. #36 Rebecca Pastore

    I have been looking for a script to rotate images in the header of my site using a css background call – This solution with the pho rotator script works great! HOWEVER, I cant use php on my site.. Does anyone have a solution using javascript, where i can still use the css background?

  37. #37 Nathan Smith

    The effect you’re trying to achieve would be very difficult to do by only
    using JavaScript. Essentially, think of it this way:

    • JavaScript = Foreground + Client-side.
    • PHP = Background + Server-side.

    You might want to try writing a JavaScript that will create a specific Div class randomly. You could then make the corrosponding backgrounds in your CSS.

  38. #38 Glenn

    Perfect! This was exactly what I was looking for, thanks!

Comments closed after 2 weeks.

FYI


Member of 9rulesSecure Hosting

Ads by Fusion

Latest Posts: All - RSS

My Book

Textpattern Solutions I had the privilege of co-writing Textpattern Solutions for the web technology publisher Friends of ED. If you want to develop a professional dynamic web site, without the hassle of writing all the server-side code from scratch, then Textpattern could be just the solution you are looking for.