Randomize Background Image

1. Above the DOCTYPE

Set up and array of filenames, which correspond to the file names of the images you are trying to randomize.

<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames

  $i = rand(0, count($bg)-1); // generate random number size of the array
  $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

1. CSS in the <head>

Normally you'd want to keep CSS out of the HTML, but we'll just use it here to echo out the random file name we selected above.

<style type="text/css">
<!--
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
-->
</style>

Comments

  1. User Avatar
    Antti
    Permalink to comment#

    You could probably do with even shorter code:

    <!–
    body{
    background: url(images/bg-0.jpg) no-repeat;
    }
    –>

    ..if there are under 10 images.

    • User Avatar
      Andrew Champ
      Permalink to comment#

      ??? I’m unsure about your method here. Where would you implement the php?

    • User Avatar
      Antti
      Permalink to comment#

      Uh-oh, something seems to have gone wrong when I submitted that message. I meant:

      background: url(images/bg-0

      .jpg) no-repeat;

      This works of course only if there are <= 10 images.

      Let's see, if it works this time…

    • User Avatar
      Chris Coyier
      Permalink to comment#

      Yeah I assumed there was some inline PHP going on there. PHP tags get stripped from WordPress comments, so if you need to post them, put a space between like this < ?

    • User Avatar
      Antti
      Permalink to comment#

      OK,

      so one more time (you probably already guess where I’m going here):

      background: url(images/bg-0.jpg) no-repeat;

      Like that!

    • User Avatar
      rotub
      Permalink to comment#

      lol :P

  2. User Avatar
    Michael
    Permalink to comment#

    Great snippet! How would I pull the images from a folder (and adds or subtracts from the list everytime the user uploads or deletes a photo from that directory)?

    mz

    • User Avatar
      Dylan
      Permalink to comment#

      Did you already find out how you can extract images from a folder?

    • User Avatar
      Der
      Permalink to comment#

      you can use the glob function, for example :

      you have a folder name ‘image’ this how is in action

    • User Avatar
      Der
      Permalink to comment#

      Sorry forgot the code :

      
      
      function randImage($path)
      {
      	if (is_dir($path)) 
      	{
      		$folder = glob($path); // will grab every files in the current directory
      		$arrayImage = array(); // create an empty array
      		
      		// read throught all files
      		foreach ($folder as $img) 
      		{
      			// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type	
      			if (preg_match('https://cdn.css-tricks.com/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
      		}
      		
      		return($arrayImage); // return every images back as an array
      	}
      	else
      	{
      		return('Undefine folder.');
      	}
      }
      
      $bkgd = randImage('image/');
      $i = rand(0, count($bkgd)-1); // while generate a random array
      $myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
      
      
      
    • User Avatar
      mr92
      Permalink to comment#

      woop, deleted my PHP Code…

      I’ve copied your PHP code above my doctype and changed randImage(‘image/’); to randImage(‘http://testserver.de/image/’);

      In the CSS-part I’ve changed something as well

      background: url(http://testserver.de/image/ ?php echo $myRandBkgd; ?>) no-repeat center center fixed;

      (of course with the opening arrow before ?php.

      Where is my mistake?!

  3. User Avatar
    Bruno Correia
    Permalink to comment#

    I wrote this one for a client. Works well. It returns the path to a random image. In addition it won’t allow the same image to load twice consecutively .

  4. User Avatar
    Bruno Correia
    Permalink to comment#

    I guess I’m not allowed to post a hyperlink on my comment above. – Sorry about that.

    • User Avatar
      teddy
      Permalink to comment#

      any chance you can share that with me, i need something like this for my wp site ive been working on

  5. User Avatar
    ryan
    Permalink to comment#

    this is not working for me for some reason…

  6. User Avatar
    Kristofer
    Permalink to comment#

    Hey thanks for this php-code/css it works great now, just modified the css a little bit and it was exactly the code i needed! :) Cheers

  7. User Avatar
    Ant

    And much better is give random class to body, and define backgrounds in main css file.

  8. User Avatar
    Rai
    Permalink to comment#

    Hello and thanks for sharing this…

    I will like to ask if this example is to apply a random image on the body? right?
    can I apply this to a #div? How I should do it?

    Blessings.
    Rai.

  9. User Avatar
    barun
    Permalink to comment#

    hello, i am little confused here.. could u please help me.. i didn’t know where to put the php file.. please help… thank you

    • User Avatar
      Gutem
      Permalink to comment#

      You have to put on your header.php, if you’re using one.
      The first code block you put ABOVE the DOCTYPE.
      The second code block you put before tag

  10. User Avatar
    neel
    Permalink to comment#

    lol: i think your scripts are not working properly.these are copy paste form net and you never use these

    • User Avatar
      Navee
      Permalink to comment#

      No my friend… $you = $followed_instructions;

      IF ($followed_instructions === true) {
      $result = “this works as written and intended “;
      $result .= “…and by reading the code ALONE without execution it works”;
      IF ($you === “are PHP aware”) { >>>NICE_SMILEY
      [h1]AWE GIVE ME THOSE CHEEKS…LOOKS LIKE SOMEONE IS GETTING A STICKER!!! [/h1]
      NICE_SMILEY;
      }
      }else{
      $result = “{$you} will assume it’s copy/paste and non-working “;
      $result .= “and that nested IF may throw you FOR a loop…and WHILE may DO more harm to you…WITH ($your_assumption) {$return false;} #JS”;
      }

      $message = “Either way…”;

      echo $message . ” ” . $result . “!”; // or use print IF echo is too copy/pasty for $you…please TRY this snippet again until you CATCH random background images appearing in your browser. #TeamHelloWorld

  11. User Avatar
    David Zupec
    Permalink to comment#

    hello, I’ve tried to implement this but for some reason it’s not working. I added the php above my doctype in my index.php page and added the php echo command inside my background tag in the css. I’m just getting a blank screen? Any help would be appreciated : )

    • User Avatar
      Navee
      Permalink to comment#

      While your screen is blank: right-click and select View Background image or equivalent to viewing background image depending on your browser! You may get an error message stating the image you are trying to preview is not available.

      I.e. wrong file path, incorrect spelling, etc. >>> double check your image file names in the php document (within the $bg ARRAY) with the file names of the images in your folder…and make sure your CSS background url image path is set correctly. Sometimes people have “image” dir (singular) and others have “images” dir (plural) or further nested image folders.

      It does not matter where your images are so as long as you point to the exact directory and have the correct spelled file names in your ARRAY it should work.

      Also it may seem obvious but make sure you ARE using a webserver capable of parsing/executing php code…other than that it is normally file paths or misspellings. But I’m sure you have ALL the above right…right? Then make sure you end your extension with .php rather .htm or .html and watch it WORK!!!

    • User Avatar
      Jornes
      Permalink to comment#

      Please make sure the php code for css part is on your html file but not in your css file alone.

      <!doctype html>
      <html>
      <head>
      <title>Your Web Page Title</title>
      <style>
      body{background: url(yourimagepath/<?php echo $selectedBg; ?>) no-repeat; /**it works this way**/
      }
      </style>
      <style src="yourcsspath/yourcss.css"></style> <---the php code won't work in this css file.
      </head>
      <body>
      Your content here.
      </body>
      </html>

      Hope it helps.

  12. User Avatar
    Feijao
    Permalink to comment#

    Hi!
    the code from the post worked for me ;)

    many thanks,
    AF

  13. User Avatar
    Aase
    Permalink to comment#

    It worked for me. Thanks. I use a css-file and it worked perect. I used the coce in a table.

  14. User Avatar
    Leimei

    Hi~ I was just wondering if this’d work for tumblr themes? ^^” I’ve been trying to learn about html all day, trying to at least alter default tumblr themes and use custom html etc, and I remember seeing banners change on another website and thought it was cool, so I wanted to do it myself and found this page, but for some reason it won’t work…

    • User Avatar
      Christopher Anderton
      Permalink to comment#

      As Tumblr is a hosted service, you can not use PHP. However, if you search, there are JavaScript options for this working on Tumblr.

  15. User Avatar
    atotalpirate

    This is awesome! Works great! Almost.. Can anyone provide insight as to why this works perfect everywhere but my blog posts page? Works fine on the blog but if you click a post the background is blank. Any help would be much appreciated!

  16. User Avatar
    Markforces
    Permalink to comment#

    Someone might need to spell it out to me about the extra php code. I’ve got the 1st php code before the doctype and the css style code in the head tag. so where does the extra php code go? I’m a self confessed php novice so be gentle. Can if go in my html document with the rest of the php or as a separate file and if so do i need to do? Cheers

  17. User Avatar
    Felipe

    Is there a way to have the background color change along with the image?

    I would like to have the page scrolled.

    • User Avatar
      Danny
      Permalink to comment#

      You could change the image names to id/class names and set it that way!? then in your css file define the colors ect.

      < ?php
      $bg = array(‘red’, ‘green’, ‘blue’); // array of class names

      $i = rand(0, count($bg)-1); // generate random number size of the array

      $selectedBg = “$bg[$i]”; // set variable equal to which random filename was chosen
      ? >

      < div class = ” < ?php echo $selectedBg; ? >” >

      then in your css file:

      .red{SET STYLES}

      .green {SET STYLES}

      .blue {SET STYLES}

  18. User Avatar
    Jornes
    Permalink to comment#

    Hey! It’s great man. The code is working for me and your instruction is simple and easy to understand!! Keep it on! I’m creating a new website for my own business. With your code, i can easily display more nice images to my clients. Thanks a lot! =)

  19. User Avatar
    Robert
    Permalink to comment#

    Nice and clean code, good use of it. Thanks a lot! =)

  20. User Avatar
    Andrew
    Permalink to comment#

    <

    p>I know I’m late to the party on this, but having tried several convoluted methods including http://sonspring.com/journal/easy-random-css-backgrounds, I was utterly staggered to see here just how “easy” it really can be.

    Thanks Chris.

  21. User Avatar
    Jacklynn
    Permalink to comment#

    Is there a way to do this on one section of a single-page scroll website? I want the main page of the website to rotate (but not the other pages on the scroll) and can’t seem to find a code that works in the CSS and not the “body” of the HTML. Right now I enter the background image in the a the div of the CSS.

  22. User Avatar
    Orange Pages
    Permalink to comment#

    Hey! Your code is not only working for background changes randomly and also work for my js code. You can look at my site the “hot search(below searchbox)” the keywords there keep changing randomly every time you reload the page. PHP code is Fantastic! Will learn more and share it to everyone later. Cheers!

  23. User Avatar
    Shem
    Permalink to comment#

    You don’t have to put the css in your HTML:
    Just put the php below in the top of your style sheet and change the file extension to php. This method lets you use variables in the rest of your styles as well.

    < ?php

    header(“Content-type: text/css; charset: UTF-8”);

    $bg = array(‘bg-01.jpg’, ‘bg-02.jpg’, ‘bg-03.jpg’, ‘etc.jpg’ );

    ? >

    html {
    background: url(images/< ?php echo $bg[array_rand($bg)]; ? >)
    }

    //the rest of your css

  24. User Avatar
    nicolap
    Permalink to comment#

    The original code correctly reloads the picture only in FF; Chrome and IE9 require ctrl+F5, that is uncommon for standard users. Am I the only one seeing this problem? Thank you.

  25. User Avatar
    joppz
    Permalink to comment#

    Hi.
    Before trying to put this yo use i was wondering:
    Can I preload the images somewhere so that the site won’t have to load big pics all the time?
    Can it be put in the CSS file instead and renaming the css to .php (lie anoter example on this site)?

    • User Avatar
      Max Shomeah
      Permalink to comment#

      first to say that I don’t like the randomizing images idea at all. most of the time sites do this, end result looks almost as disgusting as famous marquee texts, pfff.

      few comments for readers above though: using ‘glob’ or whatever ‘readdir’ will make this snippet put additional workload for webserver – scanning directory at each page load – may be costly, especially if directory is huge.

      although putting that kind of code in .css turns it to uncacheable, i.e. slows downloading of site pages for site users’ a little. from the other side, depending on your webserver settings you may find that code in .css won’t work at all, because your browser will cache it at first load and use cached version in all further requests, without any randomizing at all.

      to put long story short: the logic of snippet put by original author is JUST RIGHT, don’t mess changing.

  26. User Avatar
    Der Lee
    Permalink to comment#

    For those who have many questions, this is easier to implement :

    ////// EXAMPLE USAGE //////

    1.

        .myBackground { background:url(<?php echo randImgs('image/bkgd'); ?>) no-repeat left top; }
    
    </style>
    
    <body class="myBackground"> ... </body>
    

    — OR —

    2.
    <body style="background:url() no-repeat left top”> …

  27. User Avatar
    Der Lee
    Permalink to comment#

    Sorry about the above

    
    <?php
    
        // This can be any where, but MUST be before you echo statement
        function randImgs($path=NULL, $type='jpg|jpeg|png|gif') 
        {
            if (!is_null($path)) {
                if (!is_dir($path)) {
                    $images = glob($path.'https://cdn.css-tricks.com/*.*'); $array = array();         
                    foreach ($images as $image) {
                        if (preg_match('https://cdn.css-tricks.com/[.]('.$type.')$/', basename($img))) { $array[] = $img; }               
                    } shuffle($array); return(current($array));
                } else { return('Directory doesn\'t exist.'); }
            } else {  return('Data not found.'); }
        }
    
    ?>
    
    ////// EXAMPLE USAGE //////
    
    1.
        <style type="text/css">
    
            .myBackground { background:url(<?php echo randImgs('image/bkgd'); ?>) no-repeat left top; }
            
        </style>
    
        <body class="myBackground"> ... </body>
    
     -- OR --
     
    2.
        <body style="background:url(<?php echo randImgs('image/bkgd'); ?>) no-repeat left top"> ... </body>
    
    
  28. User Avatar
    Nabin Bajracharya
    Permalink to comment#

    This code help me much. I have use this in joomla.
    Thank you so much. and i am regular visitor and downloader of your tutor too.

  29. User Avatar
    jake percival

    Ok so what I’m trying to do i place a random background on a forum plugin (Mingle Forum). I’m also using wordpress. Is this doable? I appologize im just getting into coding personally.

    • User Avatar
      Der

      Yes, the script is very generic, as long as you follow the instruction above you should be fine
      …. oh by the way change “$image” -> “$img” after the word ” as “, is my mistake

  30. User Avatar
    let
    Permalink to comment#

    Hello everybody !
    tanks for this tuto !
    Do you know how could I give a title for this backgound image? One title for all will be great ! ☼

  31. User Avatar
    Rozgar Opps

    Can anyone figure out and tell me which of the above codes this squeeze (signup) page might be implementing to display random background image each time the page is refreshed or revisited? I figured out that there was probably no JavaScript and there were MORE than 10 images and I’m a non-techie, knowing only some HTML. Help would be highly appreciated. The squeeze page address is as below: http://promoplatinum.com/sq1/swp.php (not mine).

  32. User Avatar
    au2001
    Permalink to comment#

    This one works perfectly fine for me :<br/>
    <style type="text/css"><br/>
    html {<br/>
    background-repeat: no-repeat;<br/>
    background-attachment: fixed;<br/>
    background-size: 100% 100%;<br/>
    background-image: url(<?php echo "images/backgrounds/bg-".rand(0, 10).".png"; ?>);<br/>
    /* replace 10 by the number of backgrounds you have in images/backround/ and named bg-x.png */<br/>
    }<br/>
    </style>

    • User Avatar
      Zandstralen
      Permalink to comment#

      au2001,

      Does that work without additional php code somewhere required?

    • User Avatar
      steve saltman
      Permalink to comment#

      doh…just posted same method below… exactly…

  33. User Avatar
    au2001
    Permalink to comment#

    oups, without all the ‘<br/>’s…

  34. User Avatar
    steve saltman
    Permalink to comment#

    Here’s a simpler way:

    make sure your filenames have an integer at the end.

    In this case, I have two:
    cloud3.png
    cloud4.png

    .clouds {
    background:transparent url(‘/images/lm/clouds<?php echo rand(3,4)?>.png’) repeat top center;
    }

    if you want a random number from 1 to 100, just change the (3,4) to (1,100) and your files should be named cloud1.png, cloud2.png, cloud3.png, etc. Number your images consecutively and it will work.

    That’s it. Random background each time on page load.

  35. User Avatar
    steve saltman
    Permalink to comment#

    And here’s one for any image (don’t need to conform to any filename structure):

    background: url(<?php $a = array(‘anyfile.jpg’,’anyotherfile.gif’, ‘somefile.png’); echo $a[array_rand($a)];?>);

  36. User Avatar
    Forrest
    Permalink to comment#

    The example as Chris input it at the very beginning works fine. Just make sure you get the path to your images folder correct. For me it was /images/bg-01.jpg.

    Thanks Chris

  37. User Avatar
    klafkid
    Permalink to comment#

    Hey, thanks to au2001, your code works just great.

    I try to use the code inside the loop in wordpress, and looking at the html code of my website in the browser I get a different background for every post.

    Still there is only one picture seen for the whole page. (I want to have a random and different background for any post.) Any ideas/help?

  38. User Avatar
    emploi au maroc
    Permalink to comment#

    hi this code not work for me sameone give me full code plz

  39. User Avatar
    Immunos
    Permalink to comment#

    Hi Chris,
    thank you for this amazing script. It works fine.
    How do I change the code in order to make sure that every time when I refresh the page, a different background image is used?
    With the script listed above, it happened, that after refreshing, there is still the same bg image, which I assume is randomly chosen anyway. Can modify the code to make it display a different image every time after refreshing?
    Thanks a lot in advance,
    I

  40. User Avatar
    kevin
    Permalink to comment#

    Howdy. I see this is an old post, but I’m using WP-Super Cache for page optimization and it is preventing the random image code from working. I get the same image on every page refresh or click through to another page. When I turn off WP-Super Cache it works fine. Is there a workaround to get the random image and the caching plugin to coexist? I know very very little about how caching works but would appreciate any thoughts. Thanks, kevin

  41. User Avatar
    Nedyah
    Permalink to comment#

    Umm how about instead of random, based off of dates plese help

  42. User Avatar
    Shubho
    Permalink to comment#

    Hello,
    it works fine, no more problem at all to implement on my client site.

    Thanks !

  43. User Avatar
    Ayrton
    Permalink to comment#

    can someone tell me how to change the route of the images by default?

    instead of images / I wanted it to another folder

    thanks! :3

  44. User Avatar
    rdllngr
    Permalink to comment#

    Thank you, steve saltman. Worked perfectly! And it’s so simple…

    file3.png
    file4.png

    .class {
    background: url(‘/images/file.png’);
    }

    • User Avatar
      rdllngr
      Permalink to comment#

      Thank you, steve saltman. Worked perfectly! And it’s so simple…

  45. User Avatar
    JuiceTown
    Permalink to comment#

    Came here looking for a css trick. The php solution is trivial. I need css

  46. User Avatar
    Ron
    Permalink to comment#

    Can anyone help me – I need a random foreground and background to match. Foreground and backgrounds match in theme? I have no idea how to do two images. It can be .php or javascript.

  47. User Avatar
    Peter
    Permalink to comment#

    This works fine for me in Chrome but for some reason not in Firefox and Edge where always the same image is displayed. Any ideas?

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag