How to *named* @keyframes in SASS?

52 Views Asked by At

I'm trying to create the following set of named @keyframes using a loop in SASS

@keyframes loading-1 {
    14.28% {
        opacity: 0.3;
    }
}

@keyframes loading-2 {
    28.57% {
        opacity: 0.3;
    }
}

@keyframes loading-3 {
    42.86% {
        opacity: 0.3;
    }
}

@keyframes loading-4 {
    57.14% {
        opacity: 0.3;
    }
}

@keyframes loading-5 {
    71.43% {
        opacity: 0.3;
    }
}

@keyframes loading-6 {
    85.71% {
        opacity: 0.3;
    }
}

@keyframes loading-7 {
    100% {
        opacity: 0.3;
    }
}

I've been looking at several references including StackOverflow, and none have address the type of @keyframe naming I'm trying to accomplish, and I really don't think there's any duplicate post that solves exactly this issue.

I want to be able to do something like:

$number-of-steps: 7;

@function to-fixed($float, $digits: 2) {
    $sass-precision: 5;
    
    @if $digits > $sass-precision {
      @warn "Sass sets default precision to #{$sass-precision} digits, and there is no way to change that for now."
      + "The returned number will have #{$sass-precision} digits, even if you asked for `#{$digits}`."
      + "See https://github.com/sass/sass/issues/1122 for further informations.";
    }
    
    $pow: pow(10, $digits);
    @return round($float * $pow) / $pow;
}

   :


@for $l from 1 through $number-of-steps {

    @keyframes loading_#{$l} {
        {to-fixed((100/$l), 2)}% {
            opacity: 0.3;
        }
    }

}

But SASS complains with

Compilation Error
Error: expected "}".
   ╷
18 │     @keyframes loading-#{$l} {
                                   ^

Is there a way to dynamically create the name for these keyframes?

I'm using the "Live SASS Compiler" in Visual Code Studio, and it appears to be up-to-date.

TIA!

1

There are 1 best solutions below

0
Arkellys On

Your problem is no the dynamic names, you have two syntax errors. First is the missing # on your interpolation of to-fixed:

#{to-fixed((100/$l), 2)}% {
  opacity: 0.3;
}

And second is your use of pow(), this function is not available as is, you have to import it from sass:math:

@use "sass:math";
$pow: math.pow(10, 2);

Note that pow() is only compatible with Dart Dass since v1.25.0.