Almost all web projects I work on use a CSS pre-processor and of one of the main advantages of using one is the ability to use variables. Colours, hex or codes or otherwise, are usually one of the first pieces of repetitive code to be abstracted into variables because they’re hard to remember; when you’re trying to get stuff done you don’t want to keep looking up 6 character references, hues or luminosities.
In many of the Sass or LESS projects I’ve worked on a second layer of abstraction is also added to map the colour palette to variables which better describe their uses in an effort to avoid the potential pitfalls of being too specific:
I think colour management can go one step further and specify the relationship between colours, a process which I call themes. The implementation of the themes idea has been made very simple with the release of Sass 3.3 which introduced the
Map data structure and associated functions. Themes are just a maps defining a name and the associated colours:
My original implementation of the themes idea was for a site which used different arrangements of the colour palette for different sections of the site but I think it’s a useful technique to use on any project, the majority of which will use multiple colour variations for basic elements and components.
A client’s brand guidelines or your team’s designer will always tell you that only certain colours should be used together, a predominant colour will often have a complimentary and contrasting colour. Defining these rules in one place not only prevents duplication throughout the codebase but aids a common language between designers and developers. The single point of reference means non-developers can easily jump in and confidently make tweaks.
The aspect of this technique which really appeals to me though is that it can keep stylesheets really DRY which should aid maintainability in future. For example, simple text variations can be defined dynamically:
And variations for more complicated, stateful components can be kept really terse without creating stylesheets that lose coherency:
CSS pre-processors can make working with colours much easier over the lifetime of a project and this is just another little technique that takes advantage of the extra power. Let me know what you think about defining the relationships between colours in the comments below or check out an example.