Helpful LESS mixin to convert hex value to rgba

January 13, 2014


Recently I was trying to come up with a way to assign a LESS color variable to an element's background and give it some transparency (WITHOUT using opacity). The rgba function seemed to be the wisest choice, but I had a bunch of hex colors defined in my LESS sheet, not rgba values. Luckily, I was able to come up with a useful mixin to convert my hex colors into rgba so I could assign an alpha level to them.

[css].bg-transparent(@color, @alpha: 1) { background: rgba( red(@color), green(@color), blue(@color), @alpha); }[/css]

Example [css].rule-1 { .bg-transparent(#0b3307, .5); }[/css]

will output the following after being compiled by LESS:

[css].rule-1 { background: rgba(11,51,7,0.5); }[/css]