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.

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

Example

.rule-1 {
  .bg-transparent(#0b3307, .5);
}

will output the following after being compiled by LESS:

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

3 thoughts on “Helpful LESS mixin to convert hex value to rgba

Leave a Reply