Advanced Sass : online course

Simplify animation keyframes with unique-id()

With some creative use of the unique-id() function you don't have to keep track of the names of your @keyframes anymore. Use it in combination with a simple mixin and you only have to provide keyframe values, with Sass taking care of the rest:

Play with this gist on SassMeister.

The mixin invokes unique-id() once, storing its return value in the $animation-name variable. If we would invoke the function twice, we would end up with different values. That's not what we want. It then outputs the animation-name CSS property, using the unique identifier for its value.

It does the same for the identifier of @keyframes, encapsulating the @content directive. This will be replaced by the actual keyframes we supply to the mixin when including it. Because @-rules bubble up in Sass, we can nest it here and have it at the root of our compiled CSS.

To use this mixin, you @include the mixin in the selector you want to apply animation to. Its body will be the actual keyframes, and the mixin will take care of the rest (result on the right)!

The above is part of the Advanced Sass online course, which helps you turn your Sass up to eleven. You can become a Sass expert too!