Search code examples
csssasscss-transformsstring-interpolationscss-mixins

Pass variable from SASS mixin to CSS Value


How can we pass the value of variable $name to a CSS value.

Our $name variable = "rotateX" however transform: $name( 360deg ); doesn't seem to output transform: rotateX( 360deg );

Even if we use interpolation:

This SCSS

@mixin rotate( $name ) {
  animation-name: $name;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  
  @keyframes #{ $name } {
    100% {
      transform: #{ $name } ( 360deg );
    }
  }
}

.rotate-x {
  @include rotate( $name: rotateX );
}

Outputs this CSS:

.rotate-x {
  animation-name: rotateX;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-iteration-count: infinite; }
@keyframes rotateX {
  100% {
    transform: rotateX 360deg; } }

For some reason the parenthesis are gone around 360deg value breaking the entire CSS rule.

How can we properly add transform: rotateX( 360deg ) where rotateX is a variable?


Solution

  • It might not be the best solution. But it'll solve your problem. Try with the below code.

    @mixin rotate( $name ) {
      animation-name: $name;
      animation-duration: 5s;
      animation-timing-function: linear;
      animation-iteration-count: infinite;
      
      @keyframes #{ $name } {
        100% {
          transform: #{ $name }#{"("}360deg#{")"};
        }
      }
    }
    
    .rotate-x {
      @include rotate( $name: rotateX );
    }