I’m working on a website for a local wrestling company and one thing that was requested is having alternating backgrounds featuring different wrestlers. There are many tutorials that show you how to do this (there are different ways to do this too) but I’m going to share what I use to get this done. I find the code to be very simple and straight-forward.
You need to set up an array with the background filenames. These would be the images you want to randomize. This code is added it above the doctype declaration on your site.
Note: If you’re using HTML5, the following code would be written above the <!DOCTYPE html>
If you’re using HTML 4.01 (which contains three different declarations: Strict, Transitional and Frameset), the code would be written above the <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> (I’m using the XHTML 1.0 Transitional doctype declaration for this example)
$background = array('bg01.jpg', 'bg02.jpg', 'bg03.jpg', 'bg04.jpg', 'bg05.jpg');
$index = rand(0, count($background) - 1); // This variable declaration generates a random number that's within the size of the array
$randomBackground = $background[$index]; // This sets the variable equal to a random filename chosen from the background array
To display the random background on your page, you will have to add the following code inside the tag of your file. This will create a ‘class’ to be added to the tag later. Feel free to add any properties you may need for the background (background-repeat, background-attachment, etc.)
background: url(images/<?php echo $randomBackground; ?>);
All that’s left to do is add the CSS class randomBackground to the tag of our file, something like this:
And we’re done! You should be able to see random backgrounds every time you refresh the page. Click the button below to see a demo.