Spencer Rohan Spencer Rohan - 1 month ago 16
Sass (Sass) Question

Create a SASS mixin for animation

I want to create a mixin that allows to adjust for percentage on the fly. I'm getting a bit tripped up, would love some pointers.

Here is what I want to achieve:

@keyframes slide-1 {
0% {transform: translate3d(0, 0, 0);}
50% { }
100% {transform: translate3d(-100%, 0, 0);}
}

@keyframes slide-2 {
0% {transform: translate3d(0, 0, 0);}
50% { }
100% {transform: translate3d(-200%, 0, 0);}
}


Mixin would take an argument of percentage - and I'm assuming the animation name? Something like:

@keyframes $animation-name {
0% {transform: translate3d(0, 0, 0);}
50% { }
100% {transform: translate3d($percentage, 0, 0);}
}

Answer

You can add mixin somewhere in the top of .sass file just before it is been called. Or you can include it from the external file.

@mixin animation-mixin($name, $from, $to) {
  @keyframes #{$name} {
    0% {transform: translate3d($from, 0, 0); opacity: 0;}
    100% {transform: translate3d($to, 0, 0); opacity: 1;}
  }
}

Call the mixin and pass these 3 values $name, $from, $to like this:

@include animation-mixin(slide-1, 0, 100%);
@include animation-mixin(slide-2, 0, 200%);

And it would be translated into this:

@keyframes slide-1 {
  0% {
    transform: translate3d(0, 0, 0);
    opacity: 0;
  }
  100% {
    transform: translate3d(100%, 0, 0);
    opacity: 1;
  }
}
@keyframes slide-2 {
  0% {
    transform: translate3d(0, 0, 0);
    opacity: 0;
  }
  100% {
    transform: translate3d(200%, 0, 0);
    opacity: 1;
  }
}

DEMO

HTML

<div class="box-1"></div>
<div class="box-2"></div>

SASS

.box-1,
.box-2 {
  height: 20px;
  width: 20px;
  margin: 5px;
}
.box-1 {
  background-color: blue;
  animation: slide-1 2s ease infinite;
}
.box-2 {
  background-color: red;
  animation: slide-2 2s ease infinite;
}

@mixin animation-mixin($name, $from, $to) {
  @keyframes #{$name} {
    0% {transform: translate3d($from, 0, 0); opacity: 0;}
    100% {transform: translate3d($to, 0, 0); opacity: 1;}
  }
}

@include animation-mixin(slide-1, 0, 100%);
@include animation-mixin(slide-2, 0, 200%);