Travis L
Travis L

Reputation: 681

Doing math with LESS variables for animation keyframes

I'm trying to use LESS variables to be able to manipulate the timing on a looped keyframe animation. I'd like to make my animations work off of calculations based on a few variables, but LESS is parsing the keyframe values without doing the math.

Does anyone know if this is possible?

@sL: 15px;                      /* slide length */
@aL: 4%;                        /* animation length */
@pL: (100% - (@aL * 10)) / 2;   /* pause length (100% - length of all animations / 2) */

@-webkit-keyframes slideA {
    0%                      { left: 0; }
    @{aL}                   { left: @sL; }
    (100%-@{pL})-@{aL} * 2  { left: @sL; }
    (100%-@{pL})            { left: 0; }
    100%                    { left: 0; }
}

The LESS output is as follows:

/* slide length */
/* animation length */
/* pause length (100% - length of all animations / 2) */
@-webkit-keyframes slideB {
  0% {
    left: 0;
  }
  4% {
    left: 0;
  }
  (4% * 2) {
    left: 30px;
  }
}

Upvotes: 4

Views: 6258

Answers (1)

helderdarocha
helderdarocha

Reputation: 23637

Less has some issues with ambiguous syntaxes, for example in media-queries you might want to print 16/9 in CSS instead of calculating a division. The same might happen in some properties (such as font). For those cases, Less (1.7) does not perform the operation, unless you explicitly place it within parentheses. Another issue is with the dash, since it can be used in variables, as a unary operator, and may mean different things if there are spaces.. I am not sure about how Less deals with these issues in keyframes, but you can always be safe if you place your calculations inside variables (either top-level or scoped in mixins).

This is a version of your code using variables. It should work with no problems (try it in http://lesstester.com/):

@sL: 15px;                      /* slide length */
@aL: 4%;                        /* animation length */
@pL: (100% - (@aL * 10)) / 2;   /* pause length (100% - length of all animations / 2) */
@v1: (100% - @pL) - @aL * 2;
@v2: (100% - @pL);


@-webkit-keyframes slideA {
    0%     { left: 0; }
    @{aL}  { left: @sL; }
    @{v1}  { left: @sL; }
    @{v2}  { left: 0; }
    100%   { left: 0; }
}

Upvotes: 4

Related Questions