Skip to main content
Some time back, we needed to get a random header image on every page refresh for a client. So I devised a simple way to select a header image from any 5 given images and show it on a page. How did I do it with PHP and CSS is explained below:

Ingredients: Template File, CSS and Images

The Template File

First you need to find out the div where the random header image is going to be displayed, as its the header image then its obivious that we need to add a class to the header div. Problem is how is the single class going to have 5 different images as its background and that also changed in every page refresh.
For this just add a class called header-x, x is replaced with a random number between 1 and 5 by using PHP’s rand() function. This will require your template to be a PHP file, if you are using a CMS like Drupal then in Drupal edit the header div’s code in page.tpl.php file as below:

The CSS Code

After the template is fixed, now you have to apply a different background image to the classes 1-5. So header-1 will have header1.jpg,…. till header-5 will have header5.jpg as its background image. The code can be seen below and downloaded here.

The Images

Create 5 images of the same size and relevant to the website. You have your random header on page refresh working. Make sure the images are named correctly and placed relative to the CSS file for it to work.

In case of 5 images when page refreshes the same image may appear but in case of 10 images the chances of same image repeating is slim. Back-end Caching can also affect the PHP’s random function call.

Live Websites

Live websites to check out similar implementations: and
Hope you liked this small but effective tutorial, have fun with PHP and CSS.