Hakeem Almidan

SCSS Animation Mixin

Problem

The slightest change in CSS animations (@keyframes) requires a creation of a new animation.

Problem Example

@keyframes to-yellow {
  50% { background-color: yellow; }
}

@keyframes to-skyblue {
  50% { background-color: skyblue; }
}

Both of the animations pretty much do the same thing, but we had to create two of them. We had to create two of them because their property (background-color) had different values (i.e. yellow and skyblue).

This doesn’t follow the DRY software development principle.

To fix this, we’re going to use an SCSS mixin.

Solution

Looking at the problem example above, we’d replace it with something like this:

@mixin animation-mixin($name, $color-var) {
  @keyframes #{$name} {
    50% { background-color: $color-var; }
  }
}

@include animation-mixin(to-yellow, yellow);

@include animation-mixin(to-skyblue, skyblue);

Then you could call the to-yellow and to-skyblue animations in your selectors as needed:

div {
  height: 100px;
  width: 100px;
  background-color: whitesmoke;
  animation: to-yellow 4s ease infinite;
}

Live example:

See the Pen SCSS Animation Mixin by Abdulhakeem Almidan (@Hakeemmidan) on CodePen.


Like what you're seeing? Subscribe below to recieve notifications of new posts ⬇️

Promise not to send more than 1 email per month (not counting subscription confirmation email) 👨‍💻


comments powered by Disqus