0

I have a document with a color property that I want to use as the background for a div. I currently do the following and it works:

<li class="task" style="background-color: {{statusColor}}">

The color is saved as a hex value and I would like to add transparency to it. I read that it is possible to do this with less:

.task{
  @result: fade(red, 50%);
  background-color: @result;
}

Is there a way to use the {{statusColor}} as the argument for the fade() function?

Chris
  • 13,100
  • 23
  • 79
  • 162

1 Answers1

1

You are correct that less can add transparency with fade(). The problem with that approach is that less is part of the meteor build process and therefor cannot possibly know which document's statusColor to use. In other words, your .less files are compiled to .css at build-time, not run-time.

So you either need to store your colors in rgb format so that you can use background-color: rgba(r,g,b,a); or do the conversion on the front-end.

Here is some code to convert from hex to rgba: https://stackoverflow.com/a/19663620/211727

You could use it in a helper like this:

Template.task.helpers({
    statusColorRGBA: function(hex) {
        return 'rgba(' + parseInt(hex.slice(-6,-4),16)
        + ',' + parseInt(hex.slice(-4,-2),16)
        + ',' + parseInt(hex.slice(-2),16)
        +',0.5)';
    }
});

Usage:

<li class="task" style="background-color: {{statusColorRGBA statusColor}}">

FYI, there is currently no way to specify in alpha channel with hex notation: https://stackoverflow.com/a/31029864/211727

Community
  • 1
  • 1
ejb
  • 304
  • 2
  • 3