SmartCodingTips

CSS Keyframe Animations

Keyframe animations in CSS allow you to define complex animations by specifying styles at various points during the animation sequence. This gives you full control over how elements animate.

1. Basic Syntax

Use the @keyframes rule to define animation stages, and apply the animation using the animation property:


@keyframes slideRight {
    from {
        transform: translateX(0);
    }
    to {
        transform: translateX(100px);
    }
}

.box {
    animation: slideRight 2s ease-in-out;
}
            

2. Multiple Steps with Percentages

Define multiple stages using percentages:


@keyframes bounce {
    0%   { transform: translateY(0); }
    50%  { transform: translateY(-50px); }
    100% { transform: translateY(0); }
}

.bounce-box {
    animation: bounce 1s infinite;
}
            

3. Animation Properties

  • animation-name – the keyframe animation name
  • animation-duration – how long the animation runs
  • animation-timing-function – easing function
  • animation-delay – delay before animation starts
  • animation-iteration-count – number of repetitions (infinite allowed)
  • animation-directionnormal, reverse, alternate
  • animation-fill-mode – defines final styles after animation (forwards, backwards)

4. Shorthand Example


.animate {
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0%   { transform: scale(1); }
    50%  { transform: scale(1.1); }
    100% { transform: scale(1); }
}
            

5. Best Practices

  • Use animations to enhance UX, not distract.
  • Keep durations short (typically under 2 seconds).
  • Combine with transform or opacity for better performance.
  • Use prefers-reduced-motion media query for accessibility.

Conclusion

Keyframe animations provide fine-grained control over element motion, enabling you to create everything from subtle effects to complex interactive animations — all with pure CSS.