PHP: Random Background Image

Posted by on December 5, 2013 • Filed Under Tutorials

 

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.

Step 1: Code above the DOCTYPE

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)

Step 2: CSS in <head>

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.)

Step 3: CSS Class in <body>

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.

Step 4: See it in action!

DEMO



8 Comments


  • avatar image

    Manda

    Dec 05, 2013

    Reply

    Great tutorial! Thanks!

    • avatar image

      Nicole

      Dec 05, 2013

      Reply

      You're welcome Manda, glad it's useful! :)

  • avatar image

    Dasiy

    Dec 05, 2013

    Reply

    You made this so easy! Thanks!

  • avatar image

    Kisa Johnson

    Dec 05, 2013

    Reply

    That's very cool! I wouldn't do it on my site as it would seem too distracting for a blog, but thanks for sharing the information! I'm sure lots of people will find it helpful. :)

  • avatar image

    Jamie

    Dec 10, 2013

    Reply

    Great tutorial! Thank you!

  • avatar image

    Joy

    Dec 10, 2013

    Reply

    Ah! This is so helpful! I've been looking for something like this. I'm working on a clients website and I think they will flip over something like this. Thank you so much for this!

  • avatar image

    Sara

    Dec 15, 2013

    Reply

    I'll definitely give this script a go. I am so behind everything websites these days, but that effect is really good!

  • avatar image

    Cassie

    Jan 01, 2014

    Reply

    This is really a great post. Cool and very detailed. Thank you for sharing this very informative post

Post your comments