Converting a hex colour code to RGBA is easy - LESS CSS

Converting a hex colour code to RGBA is easy - LESS CSS

These days the use of colours with opacity (RGBA) is common. The downside is, it means the number of colour values we need to maintain multiplies and it is hard to tell when a hex value is the same as an RGB value in our CSS files. Fortunately, LESS provides us with functions to simplify this.

The Scenario

We've got our colour palette (as hex codes) for the web site we're working on and we're storing them nicely as global variables.

// base colours http://www.colourlovers.com/palette/3738/bacon_and_eggs
@alizarin-crimson:  #C84D52;
@going:             #CC7076;
@apple-meat:        #FFFFE7;
@complexion:        #F7DFA3;
@yellow-bellpepper: #FFC500;

Our design is using these colours but sometimes with various opacities. This is totally cool for us, we can use RGBA. But what do we do in these cases? Do we liberally litter our CSS with RGBA values?

.fancy-overlay {
    // I have no idea what colour this is.
    background-color: rgba(200, 77, 82, 0.4);
} 

Without using variables, an RGBA is meaningless to any developer looking at it. This approach also introduces an extra maintenance overhead should we need to change them in the future.

So add variables then

// RGBA colours
@alizarin-crimson-40-pct: rgba(200, 77, 82, 0.4);

That seems sensible, but the amount of variables could quite easily mount up and again, if a hex colour changes later on down the line I've got a much bigger maintenance overhead.

Solutions

So what approaches can we use? LESS has a number of functions that we can use to convert our hex value to RGB for us. Win!

Approach 1

First approach is to use the functions red, green, blue (see color channel functions). These functions extract that particular channel from a colour object. This means we could do this.

.fancy-overlay {
    // Now I know the colour
    background-color: rgba(red(@alizarin-crimson), green(@alizarin-crimson), blue(@alizarin-crimson), 0.4);
}

which outputs

.fancy-overlay {        
    background-color: rgba(200, 77, 82, 0.4);
}

That's great, I'm able to use my colour variables, although it is fairly verbose. I wonder if there is a better approach?

Approach 2

There is one final function that we can use to make it more concise and easier to use. fade.

Set the absolute transparency of a color. Can be applied to colors whether they already have an opacity value or not.

So now we can set our background colour like so. This time setting the opacity as a percentage.

.fancy-overlay {
    // This is more like it
    background-color: fade(@alizarin-crimson, 40%);
}

outputting

.fancy-overlay {        
    background-color: rgba(200, 77, 82, 0.4);
}

So there you have it. It is possible to get RGBA colours from your hex values, whilst keeping your CSS concise and easily maintainable!