How do I randomly change the background image on reload?

HTML, CSS and anything else that deals with client side capabilities.

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

How do I randomly change the background image on reload?

Post by simonmlewis »

Code: Select all

<style>
.home-banner
{
position: relative;
    /* The image used */
    background-image: url('../images/banner-home.jpg');
    /* Full height */
    height: 83%; 
    /* Create the parallax scrolling effect */
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
</style>
The idea is that each time the page loads, it can load a different image, maybe from a set of three.
I've seen how to do when the image is directly in the DIV, but not as a background.

And coding the background-image code into the HTML is bad-form. So is there a good way to do it?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How do I randomly change the background image on reload?

Post by requinix »

Either
a) Use a random path in the CSS itself.
b) Point the CSS to a PHP script and have it randomize the image.

The latter is probably your best bet.

Code: Select all

background-image: url('../images/banner-random.php');

Code: Select all

<?php

$images = array(
	'banner-home.jpg',
	...
);
$image = $images[array_rand($images)];

$filename = __DIR__ . '/' . $image;

header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($filename));
readfile($filename);
Post Reply