Dynamically creating an array of colors for use in inline CSS
When working with a talented team of designers, developers are often confronted with new and interesting challenges in order to make a site look great. And sometimes (all the time) we developers tend to react to such challenges with theatrical proclamations like, “It simply cannot be done!” or — my personal favorite — “Inconceivable!” But, as we all know in our hearts, there is usually a solution to be found and a design to fully realize.
I was confronted with a recent example of such a problem when a design called for an ordered list of 3 columns, each column with a different color. Simple enough, right? Well, upon closer inspection, it appeared that every single list item was a different color, subtly changing as if the list itself were a gradient:
After going through the 3 stages of developer doubt (“it can’t be done”, “welll maybe…”, and “what if I…”), it dawned on me that we represent colors mathematically all the time, so shouldn’t there be a way to use math to figure this out? Bingo.
A simple function can be devised in just about any language that takes a start color, an end color, and a size (the number of ‘steps’ you want to create), and spits out an array of colors as beautiful as any rainbow! The array can then be used to generate inline CSS that solves this design conundrum.
Below is a function that accomplishes this task in PHP (note that it converts hex values to RGB in order to simplify the math).
function get_gradient_array( , , ) { = hexdec(substr(, 0, 2)); = hexdec(substr(, 2, 2)); = hexdec(substr(, 4, 2)); = hexdec(substr(, 0, 2)); = hexdec(substr(, 2, 2)); = hexdec(substr(, 4, 2)); = array(); for ( = 0; < ; ++ ) { = round( - ( - ) * ( / (-1))); = round( - ( - ) * ( / (-1))); = round( - ( - ) * ( / (-1))); [] = 'rgb(' . . ', ' . . ', ' . . ')'; } return ;}
Happy coloring!