Search code examples
csslessless-mixins

Less does not compute arithmetic expressions


I'm working in this code:

.vertical-align (@numoflines) {
  @first: (55 - (@numoflines * 5)) / 100;
  @result: percentage(@first);
  top: @result;
  -webkit-transform: translateY(@result * -1);
  -ms-transform: translateY(@result * -1);
  transform: translateY(@result * -1);
  position: relative;
}

.back {
  .vertical-align(1);
  text-align: center;
  transform: rotateY(180deg);
}

It compiles ok but when I inspect the code in Chrome it says that the @result is not a number (NaN%).

P.S: If a try this code in http://lesstester.com/ it works fine so i'm a bit messed up


Solution

  • (So to not leave this one w/o an answer, though it's a bit broader than I'd like it to be):

    Most likely lesstester.com and your project have different --strict-math settings (lesstester: off (default) and in your project it's on).

    To make your code compilable with either setting always add parens around arithmetic expressions, i.e.:

    @first: ((55 - @numoflines * 5) / 100);
    

    (in your snippet with --strict-math=on the statement will result in a list of values instead of a single value hence percentage returns NaN for it.)

    Additionally, other statements in the snippet require parens too (if compiled with --strict-math=on). For example

    translateY(@result * -1);
    

    should be

    translateY((@result * -1));
    

    otherwise it results in invalid CSS like transform: translateY(180deg * -1); too.

    Yes:

    in fact --strict-math=on is usually pain in the ass... So at some point it could be reasonable to consider if you can turn it off (unfortunately it's not always possible and depends on the libraries your project uses, e.g. recent Bootstrap versions require it to be on for example).