Search code examples
cssvariableslesshsl

Trying to use variables in HSL function (color functions take numbers as parameters)


I'm getting this error while trying to compile a HSL function:

http://codepen.io/anon/pen/GJVbzB?editors=010

@baseColor: #003459;
@randomVar: `Math.floor(Math.random()*10 + 90).toString()`;
@color: ~"@{randomVar}%";
@new: hsl(hue(@baseColor), @color, @color);

If I'm using the @test variable, it works! How is that possible and what am I wrong?

The rough thing is that this function wants percentage and I had to find a way to concat the result of the math.random with an "%".


Solution

  • Your analysis of the problem is spot on. The hsl() function does need a percentage value as input. But the problem was in the way you were creating the percentage input.

    There were two problems and they are as follows:

    • You were using .toString() which was converting the number into a String. This is not needed. You can just remove it altogether.
    • Second thing to note is that you were using String concatenation to convert the random number into a percentage. This means that the value formed is a String and no longer a percentage or a number. You can avoid this by multiplying the @randomVar with 1% which would automatically make it a percentage.

    The below snippet (having both those corrections done) should work for you:

    .randomColor() {
        @baseColor: #003459;
        @randomVar: `Math.floor(Math.random()*10 + 90)`;
        @color: @randomVar * 1%;
        @new: hsl(hue(@baseColor), @color, @color);
        @test: 25%;
    }
    
    .generate-bg-color(@spanNumber, @i: 1) when (@i =< @spanNumber) {
        span:nth-child(@{i}) {
            .randomColor();
            background-color: @new;
      }
      .generate-bg-color(@spanNumber, (@i + 1));
    }
    .generate-bg-color(24);
    

    When you assign a percentage value directly to a variable (like @test: 25%), Less compiler by default treats it as a number (or a percentage) instead of as a String and hence doing so does not cause any problems.


    You also have a couple of other options among which one is to use the unit() function as mentioned in nils answer and the other is to use the built-in percentage() function like in the below snippet. All of them do pretty much the same thing but a multiplication by 1% is a bit more intuitive in my opinion.

    .randomColor() {
        @baseColor: #003459;
        @randomVar: `Math.floor(Math.random()*10 + 90)`;
        @color: percentage(@randomVar / 100);
        @new: hsl(hue(@baseColor), @color, @color);
        @test: 25%;
    }
    
    .generate-bg-color(@spanNumber, @i: 1) when (@i =< @spanNumber) {
        span:nth-child(@{i}) {
            .randomColor();
            background-color: @new;
      }
      .generate-bg-color(@spanNumber, (@i + 1));
    }
    .generate-bg-color(24);