Building Accessible Animations with prefers-reduced-motion

Abdulqudus Abubakre - Nov 26 '23 - - Dev Community

Animations can be beautiful, but some animations can also be triggering for some users, and that's why electronic devices provide ways to turn off animations, e.g:

  • Android => Settings > Accessibility > Remove Animations
  • iOS => Settings > Accessibility > Motion
  • Windows 10 => Settings > Ease of Access > Display > Show animations in Windows
  • Windows 11 => Settings > Accessibility > Visual Effects > Animation Effects
  • MacOS => System Preferences > Accessibility > Display > Reduce motion

To ensure the animations in our web application respect these settings, we need to make use of the prefers-reduced-motion CSS feature to detect the user settings and carry out appropriate actions. In the example below, we have a simple button that by default has a pulse animation;

<button class="btn btn--animated">Fancy Animation</button>
Enter fullscreen mode Exit fullscreen mode
@keyframes pulse {
  50% {
    transform: scale(1.2);  
  }

  to {
    transform: scale(1);
  }
}

.btn {
  background: #577FAE;
  color: #FFF;
  padding: 10px 20px;
  margin: 30px;
  border: none;
}

.btn--animated {
  animation: pulse 1s linear infinite;
}
Enter fullscreen mode Exit fullscreen mode

To disable any animation if the user has it turned off using the prefers-reduced-motion feature, we can add the following block to our CSS;

@media (prefers-reduced-motion) {
  .btn--animated {
    animation: none;
  }
}
Enter fullscreen mode Exit fullscreen mode

And that's it, with just a few lines of code, we're able to make our animated button accessible, which is sufficient to pass the WCAG Criterion 2.3.3

. . . . . . . . . . . . . . . . . .