While recently designing a website I was required to build a function that would change the sites colour palette each time the visitor goes to a new page. Essentially this means each time a page is loaded I need some random element that I can assign a collection of pre-determined palette styles. The easiest way I could think of, would be to create a PHP function that would randomly return one of a set number of strings that I could then place as class on the body tag. Then in the stylesheet the background colours, logos and images can be set to each of the various classes.

This sounds more completed than it really is. PHP has a nice little function called ‘rand’. The first argument allows you to set a min point and the second argument sets the max point. The function then returns a pseudo-random integer between min and max.

This is how I used the function:

function random($max){
$random = rand(1, $max);
$bgClass = "randomClass".$random;
return $bgClass;

Just call this function in the class attribute of the body tag, replacing max with a number.

<body class="<?php echo random(5); ?>">

Then all that needs to be done is, in the stylesheet , set rules for each of the possible classes.

.randomClass1 div{background:black;}
.randomClass2 div{background:green;}
.randomClass3 div{background:red;}
.randomClass4 div{background:pink;}
.randomClass5 div{background:blue;}

Take a look at this extremely ugly demo to see the function in action. Remember to refresh the page a few times.