CSS Animation Patterns

CSS Animation Patterns

If you don’t have time to read but want to know what’s there in this post. Find the quick read 👇

Quick Read about Animation Patterns

On this Post

In this post, we are going to look at the commonly used animation patterns. These patterns demonstrate how we can create engaging animations and interactions while still respecting users’ preferences for motion. They also support all modern browsers, so you can use them with confidence.

  1. Animated Letters

  2. Animated Words

1. Animated Letters

This pattern shows how to create infinitely animated letter effects that respect the user’s motion preferences.

The goal is to animate progressively. The text should be readable by default, with the animation built on top. Split text motion effects can get extravagant and potentially disruptive, so we will only manipulate HTML, or apply motion styles if the user is OK with motion.

* Creating the reduced motion conditional variables for CSS and JS

@media (prefers-reduced-motion: reduce)

Media query will be used from CSS and JavaScript in this project. This media query is our primary conditional for deciding whether to split text or not. The CSS media query will be used to withhold transitions and animations, while the JavaScript media query will be used to withhold the HTML manipulation.

* Preparing the CSS conditional

PostCSS has been used to enable the syntax of Media Queries, where you can store a media query boolean into a variable

@custom-media --motionOK (prefers-reduced-motion: no-preference);

* Preparing the JS conditional

In JavaScript, the browser provides a way to check media queries, I used destructuring to extract and rename the boolean result from the media query check

const {matches:motionOK} = window.matchMedia(
'(prefers-reduced-motion: no-preference)'
)

I can then test for motionOK, and only change the document if the user has not requested to reduce motion.

if (motionOK) {
// document split manipulations
}

The user is OK with motion; text split into multiple elements

Stopping the motion in the render

2. Animated Words

This pattern shows how to create infinitely animated word effects that respect the user’s motion preferences.

Similar to splitting letters, this function takes a string and returns each word in an array.

export const byWord = text =>
text.split(' ').map(span)

The split() method on JavaScript strings allows us to specify which characters to slice at. I passed an empty space, indicating a split between words.

Congratulations!!!