Colours with LESS

I’ve recently taken up using LESS for my projects.
While I feel that nesting can create some truly unnecessarily specific rules when compiled it is useful for making the repetitive stuff a lot easier – churning out vendor-prefixes for example.

The main thing I use it for is remembering colours. Rather than having to keep copy-pasting hex and rgba values from random places in my files I create variables for all the colours and call them with a little mixin. This makes applying colours (transparent and otherwise) a lot easier. PLUS I get to spell colour properly!

I used a modified form of the most common one that converts hex values into RGBA. However, when the colour had no alpha it compiled 2 hex properties. That’s a bit pointless!

I’ve since come up with this:


.Colour(@color, @alpha: 1) when (@alpha = 1) {
color: @color;
}
.Colour(@color, @alpha: 1) when (@alpha < 1) {
color: @color;
color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);
}

.BGColour(@color, @alpha: 1) when (@alpha = 1) {
background-color: @color;
}
.BGColour(@color, @alpha: 1) when (@alpha < 1) {
background-color: @color;
background-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);
}

It's a very simple if statement that covers 'color' and 'background-color' and prevents LESS from duplicating properties for no reason.

The only thing this doesn't account for is when you choose a different 'base' colour for those browsers that don't support RGBA or HSLA. I may write something to take it into account when I encounter the issue but for now, this does me nicely.