77
How to add @keyframes animation code in SCSS
While working on one of my app projects, I found an error during the deployment phase. The error was referring to CSS. The app was working perfectly fine in the development mode. So what went wrong!
Since it wasn't a big project, and there was only one stylesheet, I commented out some parts of the stylesheet that were fairly simple and straightforward. I firstly guessed the error to be arising from the wrong use of interpolation i.e
#{&}
which is often used in SCSS. But it was correctly coded.
My second guess was that there is an error arising from the way @keyframes have been used. Yes, I was correct.
So, what went wrong!
In a CSS stylesheet, @keyframes animation code looks like this -
@keyframes animation-name{
keyframe-selector{
CSS property value
}
}
You create @keyframes and call animation property for different elements.
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
If you check through SCSS documentation, it has many style rules such as @mixin
,@include
,@extend
etc. But, if we use @keyframes directly, SCSS throws an error during deployment. One can infer that it is unable to recognise CSS @keyframes syntax.
It is essential to use the syntax and rules as mentioned in SCSS.
Firstly, create a @mixin for animation that includes the animation properties as arguments. It will make it easier for a developer to include this @mixin for different elements. Mostly, animation rules contain animation-name, duration, timing-function and iteration-count. You can add as many arguments as you wish.
@mixin animate($animation,$duration,$method,$times){
animation: $animation $duration $method $times;
}
Secondly, create another @mixin that includes CSS @keyframe
animation rule inside it.
@mixin keyframes($name){
@keyframes #{$name}{
@content;
}
}
For instance, we want to add fade animation property to an element with class - 'headline'.
.headline{
@include keyframes(fade){
0%{
opacity: 1;
}
50%{
opacity: 0.5;
}
100%{
opacity: 0;
}
}
@include animate(fade, 1s, linear, 1);
}
Also, another way to reduce error in this scenario is to provide different animation names for various elements even if they use the same property transitions.
So, if you get stuck while deploying your website, check for the CSS preprocessor's style rules and syntax.
This is one of the ways of using the @keyframes animation rule in SCSS.
77