Easy random CSS backgrounds
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.
rotator.txtfrom A List Apart, rename it
- Put the images to be rotated in the same directory as
- 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:
<div id="rotator"> </div>
background: url(images/rotator.php) no-repeat center top;
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
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.
<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…
altcorresponding attribute needed, since it's not content.
- It's very easy to maintain and can be used site-wide.
Note: special thanks to Jonathan Snook for his expert input.