Helpful LESS mixin to convert hex value to rgba

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);


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

will output the following after being compiled by LESS:

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

Join the Conversation


  1. I am using this for create this tool. is it perfect jS code for create a hextorgba convert tool?
    $(document).ready(function() {

    function hex2rgba_convert(hex,opacity){
    hex = hex.replace(‘#’,”);
    r = parseInt(hex.substring(0,2), 16);
    g = parseInt(hex.substring(2,4), 16);
    b = parseInt(hex.substring(4,6), 16);

    result = ‘rgba(‘+r+’,’+g+’,’+b+’,’+opacity/100+’)’;
    return result;
    var color = $(‘#hexcolor’).val();
    var opacity = $(‘#opacity’).val();
    return false;

Leave a comment

What do you think?

%d bloggers like this: