Random Color CSS3 Animation

Ever since I wrote my first lines of code, I have had a strange interest in the functions that generate random numbers. (and yes, I know actual random doesn’t exist) Every time I just want to fool around with some code, you will find me popping in a random function in somewhere. Be it CSS3 Snow, or just randomly positioned squares, I will find a way to waste my time.

So when I started playing around with CSS3 Animations the urge to use more random was always lurking around many a corner.

I ended up writing a 50 frame CSS3 Animation that just looped through a bunch of random colors.

For this I created the following PHP function;

Create random color values

This function creates lines of background properties with shorthand hex values. The shorthand makes sure that any random color will be different enough from another.

function create_animation_frame($num)

$hex_values = array(
    $current_hex = "";

    for($i=0; $i<3; $i++)
        $rand = rand(0,15);
        $current_hex .= $hex_values[$rand];

    return $num."% { background: #".$current_hex."; }";



This function got called 50 times in the following context;

@-webkit-keyframes disco { 
        echo create_animation_frame($i);
        $i++; // Add another value to $i. Remove line = 100 frames.

Enable the animation

Attach the animation to an element of your choice. I chose to add the animation to the body.disco selector, so I could toggle the party with a single line of jQuery.

body.disco {
    background: #000;
    -webkit-animation-name: disco;
    -webkit-animation-duration: 2s;
    -webkit-animation-iteration-count: infinite;

Check out the somewhat more extended example by clicking on the link to activate the disco inferno. Disclaimer: I will not be held responsible for any epileptic seizures induced by the example.

Update: Since some people opted for the idea of using this at a party, I added a GET variable, so you can now approach the example with ?text=Party%20Hard (ie. http://media.miekd.com/disco/?text=Party%20Hard and enjoy custom text.