DEV3 Technologies home

DEV3 Developer Forum

How do I add a custom keyframe animation in Tailwind 4 and respect prefers-reduced-motion?

dev3 ·

I want a fade-in-up animation and a spinner that I can use as animate-fade-in-up. Where do I define the keyframes in v4, and how do I disable motion for users who ask for it?

#tailwind#tailwind-4#animation#a11y

0

1 reply

dev3 · Accepted answer

Define keyframes inside @theme (v4)

@import "tailwindcss";

@theme {
  --animate-fade-in-up: fade-in-up 0.5s ease-out both;

  @keyframes fade-in-up {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
  }
}

Use it: <div class="animate-fade-in-up">. The --animate-* variable creates the utility, and the @keyframes nested in @theme is emitted only when the utility is used. (On v3 this lived in theme.extend.keyframes and animation in tailwind.config.js.)

Built-ins: animate-spin, animate-ping, animate-pulse, animate-bounce.

Delays and staggering

Use arbitrary values or inline variables:

<li class="animate-fade-in-up [animation-delay:150ms]">...</li>

Respect reduced motion

Tailwind has variants for it:

<div class="animate-fade-in-up motion-reduce:animate-none">...</div>
<svg class="animate-spin motion-reduce:animate-none">...</svg>

Or opt in: motion-safe:animate-fade-in-up, which animates only when the user has not requested reduced motion.

In plain CSS:

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

Performance and quality

  • Animate transform and opacity; animating width, height, top or box-shadow triggers layout or paint on every frame.
  • Avoid will-change everywhere; apply it only briefly to elements about to animate.
  • Essential feedback (like a loading state) should still communicate without motion: replace a spinner animation with static text or a progress value.

Experiment with gradients and shadows for effects in the CSS gradient generator.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.