Search code examples
sassmixins

is there a way to escape @ when writing Mixins in SASS?


I am trying to write a mixin for animations in css3. An animation in css3 requires an @keyframe. But a mixin declaration in SASS (and other declarations) start with @ too. Like @mixin, @for, etc... So what I was trying to do writing a mixin for an animation (I was trying to have all automated inside the mixin) was to put the @keyfram escaped for SASS when passed to CSS not to interpret the @keyframe's @. Is it possible to do this?

Example :

@mixin animation(
//variables :
$mykeyframe:mykeyframe,
$prop1:background,
$value1-i:white,
$value1-e:red,
$prop2:color,
$value2-i:black,
$value2-e:white,
$prop3:font-weight,
$value3-i:400,
$value3-e:bold,
$time:5s,
$iteration-count:1,
$timing-function:linear,
$delay:0s,
$direction:normal,
$play-state:running
)

{//HERE'S THE PROBLEM :
  @keyframes $mykeyframe{
    0%{$prop1:$value1-i; $prop2:$value2-i; $prop3:$value3-i}
    100%{$prop1:$value1-e; $prop2:$value2-e; $prop3:$value3-e}
  }

  -webkit-animation: $mykeyframe $time $iteration-count; /* Chrome, Safari 5+ */
  -moz-animation: $mykeyframe $time $iteration-count; /* Firefox 5-15 */
  -o-animation: $mykeyframe $time $iteration-count; /* Opera 12.00 */
  animation: $mykeyframe $time $iteration-count; /* Chrome, Firefox 16+, IE 10+, Opera 12.10+ */

  /* Chrome, Firefox 16+, IE 10+, Opera 12.10+ */
  animation-timing-function: $timing-function;
  animation-delay: $delay;
  animation-direction: $direction;
  animation-play-state: $play-state;
  /* Safari and Chrome: */
  -webkit-animation-timing-function: $timing-function;
  -webkit-animation-delay: $delay;
  -webkit-animation-direction: $direction;
  -webkit-animation-play-state: $play-state;
}

Solution

  • Even though the mixin (@mixin) and conditional (@for, @if etc.) directives in SASS start with the symbol @, you can still use it for other keywords that are not part of the SASS library like if, mixin etc.

    So, you can still do:

    @mixin animation($mykeyframe:mykeyframe) {
      @keyframes $mykeyframe {
    
    
      }
    }
    
    body {
      @include animation(someframe);
    
    }
    

    and this will generate:

    body {
      @keyframes someframe {}
    }