Animation and respecting motion preferences
Smooth transitions that perform well and do not harm people sensitive to motion.
.btn {
transition: transform .15s ease, box-shadow .15s ease;
}
.btn:hover { transform: translateY(-2px); }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: .5; }
}
.loading { animation: pulse 1.2s ease-in-out infinite; }Performance
- Animate
transformandopacity: the browser can run them on the GPU without recalculating layout. - Avoid animating
width,height,top,leftormargin. They force layout work on every frame. - Use
will-changesparingly, only on elements that really animate, and remove it afterwards. - Keep animations short: 100 to 300 ms for interface feedback.
Respect the user
Large movement, parallax and spinning can cause nausea or distraction for some people. Operating systems have a "reduce motion" setting, and CSS can read it.
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: .01ms !important;
animation-iteration-count: 1 !important;
transition-duration: .01ms !important;
scroll-behavior: auto !important;
}
}- Content must not depend on an animation to be understood.
- Anything that moves for more than 5 seconds needs a way to pause or stop it (WCAG).
- Never flash more than three times per second: it can trigger seizures.
NoteThe View Transitions API and scroll-driven animations can replace much JavaScript animation code. Treat them as progressive enhancement.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.