0
0
SASSmarkup~5 mins

Animation mixin patterns in SASS

Choose your learning style9 modes available
Introduction

Animation mixin patterns help you reuse animation code easily. They save time and keep your styles neat.

When you want to apply the same animation to many elements.
When you want to change animation details quickly in one place.
When you want to keep your CSS organized and avoid repeating code.
When you want to create smooth effects like fades or slides on buttons or images.
Syntax
SASS
@mixin animation-name($duration, $timing, $delay) {
  animation-name: animation-name;
  animation-duration: $duration;
  animation-timing-function: $timing;
  animation-delay: $delay;
  animation-fill-mode: forwards;
}

Use @mixin to define reusable animation code.

Pass parameters like duration and delay to customize animations.

Examples
This mixin creates a fade-in effect with a customizable duration.
SASS
@mixin fade-in($duration: 1s) {
  animation: fadeIn $duration ease-in forwards;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
This mixin slides an element from right to left by a set distance.
SASS
@mixin slide-left($distance: 100px, $duration: 0.5s) {
  animation: slideLeft $duration ease-out forwards;
}

@keyframes slideLeft {
  from { transform: translateX($distance); }
  to { transform: translateX(0); }
}
Sample Program

This code defines a fade-in animation mixin and applies it to a button. The button will smoothly appear over 3 seconds when the page loads.

SASS
@mixin fade-in($duration: 2s) {
  animation: fadeIn $duration ease-in forwards;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.button {
  @include fade-in(3s);
  background-color: #3498db;
  color: white;
  padding: 1rem 2rem;
  border: none;
  border-radius: 0.5rem;
  font-size: 1.25rem;
  cursor: pointer;
  display: inline-block;
  margin: 2rem;
}

/* HTML example to use with this CSS:
<button class="button">Click me</button>
*/
OutputSuccess
Important Notes

Always define @keyframes for your animations when using mixins.

Use animation-fill-mode: forwards; to keep the final animation state visible.

Test animations in different browsers to ensure smooth performance.

Summary

Animation mixins let you reuse and customize animations easily.

They keep your styles clean and save time.

Use parameters to change animation speed, delay, or distance.