Keyframe animations with SCSS not working

dcpomfret picture dcpomfret · Oct 18, 2015 · Viewed 14.9k times · Source

I'm new to keyframe animations and after some searching this article seemed like a good place to start.

Here is the articles code in codepen - http://codepen.io/anon/pen/yYPxJM

@mixin keyframes($animation-name) {
  @-webkit-keyframes $animation-name {
    @content;
  }
  @-moz-keyframes $animation-name {
    @content;
  }  
  @-ms-keyframes $animation-name {
    @content;
  }
  @-o-keyframes $animation-name {
    @content;
  }  
  @keyframes $animation-name {
    @content;
  }
}

@mixin animation($str) {
  -webkit-animation: #{$str};
  -moz-animation: #{$str};
  -ms-animation: #{$str};
  -o-animation: #{$str};
  animation: #{$str};      
}

@include keyframes(slide-down) {
  0% { opacity: 1; }
  90% { opacity: 0; }
}

.element {
  width: 100px;
  height: 100px;
  background: black;
  @include animation('slide-down 5s 3');
}

However, it doesn't work "as is" and I'm not sure how to proceed.

I'm going to be animating objects as I scroll down the page. For example animating the some to fade-in, others to scale (call to action) to make them pop. The jQuery shouldn't be an issue, it's these animations that are causing me the issues.

Would love some help to understand what I'm failing to do right.

Thanks in advance!

Answer

halfzebra picture halfzebra · Oct 18, 2015

You have to use Interpolation: #{}, so your $animation-name is not treated as CSS.

Here's my favorite article on the matter: All You Ever Need to Know About Sass Interpolation

Please, have a look at the code:

@mixin keyframes($animation-name) {
  @-webkit-keyframes #{$animation-name} {
    @content;
  }
  @-moz-keyframes #{$animation-name} {
    @content;
  }  
  @-ms-keyframes #{$animation-name} {
    @content;
  }
  @-o-keyframes #{$animation-name} {
    @content;
  }  
  @keyframes #{$animation-name} {
    @content;
  }
}

@mixin animation($str) {
  -webkit-animation: #{$str};
  -moz-animation: #{$str};
  -ms-animation: #{$str};
  -o-animation: #{$str};
  animation: #{$str};      
}

@include keyframes(slide-down) {
  0% { opacity: 1; }
  90% { opacity: 0; }
}

.element {
  width: 100px;
  height: 100px;
  background: black;
  @include animation('slide-down 5s 3');
}