
Using PHP to create random CSS
A little bit of imagination can go a long way when it comes to trying to make your website stand out from the crowd. I’m going to be looking at how we can use a simple snippet of PHP to randomly change the styles in your website design. I’ll simply be using variations of text colour, background colours and background images for the purpose of this tutorial.
The idea behind what we are doing is quite simply, use PHP to generate a random number and depending on what that random number is, we assign a value, which becomes a prefix within our CSS.
Creating the Designs and CSS
Firstly, we must create the HTML and CSS for our design variations. I’ve fundamentally used generic styles for for the layout and structure of the page, but intend to use specific classes, in order to vary the colours and certain images of my page.
Now in order to keep things nice and simple, I’ve sectioned off an area of the stylesheet for each of the three variations, keeping all my styles in one CSS document. There is no reason why you couldn’t create three separate stylesheets if you please.
Here comes the PHP…
Now as I’ve already mentioned, the PHP simply generates a random number between 1 and 3, from which, we then assign a prefix for use within our html…
Include this into your page, within the required PHP tags, either before your header or within your header, I’ve done it before as I’ve also included the randomly assigned prefix into the title tag.
$randno = rand(1,3);
switch($randno){
case 1:$prefix='winter';
break;
case 2:$prefix='night';
break;
case 3:$prefix='sunset';
break;
}
Using the Prefix…
Now we have the prefix stored as a variable, we can simply ‘echo’ it within the HTML, everywhere that we require design variation. Remember to use PHP tags when inserting into your HTML
echo $prefix;
Styling the prefix…
Now with the prefix included in the class names, the pre-created stylesheet should now give us the desired results.
/* Sunset Styles */
.sunset_bg { background:url(images/sunset_bg.jpg) repeat-x;}
.sunset_header { background:url(images/sunset_header.jpg) no-repeat;}
.sunset { color:#ab2d02;}
.sunset_refresh { background-color:#ab2d02;}
Try it in your Website Design
I’ve included all of the files for you to download and see in action. This website design idea is very simple but can be used in many different situations, from randomly generating design variations, to displaying random content, products or even videos.




I love this idea! I am definitely going to use this at some point in my website. It looks so clean, and the small amount of code hopefully shouldn’t be too difficult… I hope. PHP isn’t one of my strongest points if I’m honest but I’ll certainly give it a try!
thank you! was looking for this!