John Ohara John Ohara - 1 month ago 15
Less Question

Less CSS fade function not working with variable

i'm using Less CSS with bundler, which I build on an Asp.Net platform.

I have the following code:

&::after {
.ScaleX(0);
.Transition(0.2s 0.2s);
background-color: fade(@accentColor, 12%);
border-radius:0.2rem;
height:100%;
top:0;
z-index:-1;
}


It fails to complile.

If I change the background-color like this, it works:

background-color:@accentColor;


I set my color palettes like this:

.AccentPalette(orange);

.AccentPalette(@palette; @color:500) {
.Swatch(@palette);

@accentColor:~"@{accent@{color}}";

@accent50: @50;
... and some more
}

.Swatch(orange)
{
@50: #fff3e0;
@100:#ffe0b2;
@200:#ffcc80;
@300:#ffb74d;
@400:#ffa726;
@500:#ff9800;
@600:#fb8c00;
@700:#f57c00;
@800:#ef6c00;
@900:#e65100;
}


Any ideas?

Answer

It fails to compile because the @accentColor variable seems to contain a String and not a Color as its value. The fade() function only works on color values.

To fix the problem, convert the String into the Color value by using the color() function.

background-color: fade(color(@accentColor), 12%);

The value is being considered as a String because of the below interpolation statement. The e() or the ~"value" function outputs a String.

@accentColor: ~"@{accent@{color}}"; 

As pointed out by seven-phases-max in his comment, the below approach would also avoid the need for the color() function.

.AccentPalette(@palette; @color:500) {
  .Swatch(@palette); 
  @accentColor: "accent@{color}"; /* note the change, we are just concatenating and not evaluating */
  @accent500:  @500;

  &::after {
    background-color: fade(@@accentColor, 12%); /* actual evaluation happens here */
    border-radius:0.2rem;
    height:100%;
    top:0;
    z-index:-1;
  }  
}