Home Web Front-end CSS Tutorial How to Play and Pause CSS Animations with CSS Custom Properties

How to Play and Pause CSS Animations with CSS Custom Properties

Mar 28, 2025 am 10:18 AM

Play and pause of CSS animations: Use CSS custom properties to fine control

This article discusses CSS @keyframes animation, focusing on how to pause and control animation. Although animation-play-state property can be used to cooperate with JavaScript for control, there are many details. We will introduce a more flexible setup method that uses CSS custom properties to enable fine control of animations.

How to Play and Pause CSS Animations with CSS Custom Properties

The importance of pausing animations

When developing a CSS-driven slide, I noticed an interesting phenomenon: animations that are not in the window are still running! This makes me think: Are these running animations still consuming CPU/GPU resources, thus affecting page performance?

Although the DevTools' performance panel cannot directly display the animation consumption of "off-screen" frames, the animation does not pause when scrolling away from the slide and returning again, but continues to run to the next screen.

Therefore, it is crucial to study how animations are paused, which is related to:

  1. Performance: Avoid unnecessary resource consumption.
  2. Control: Provides user control over animation.
  3. Accessibility: Considering that some users may be sensitive to animations.

Basic ways to pause animation

In CSS, the only way to pause the animation is to use animation-play-state property and set its value to paused :

 .paused {
  animation-play-state: paused;
}
Copy after login

In JavaScript, this property is animationPlayState , and the setting method is as follows:

 element.style.animationPlayState = 'paused';
Copy after login

We can create a play/pause toggle by reading the current value of animationPlayState :

 const running = element.style.animationPlayState === 'running';
element.style.animationPlayState = running ? 'paused' : 'running';
Copy after login

Another way to pause animation is to set animation-duration to 0s . The animation is actually still running, but since the duration is zero, no action is seen. However, this is not a real pause.

Direct removal of animation ( animation: none !important; ) is not a real pause either.

Custom properties with data attributes and CSS

We use data attributes (such as data-animation ) as the CSS selector and use CSS custom attributes as the value of the animation attribute:

<div data-animation=""></div>
Copy after login
 [data-animation] {
  animation:
    var(--animn, none)
    var(--animdur, 1s)
    var(--animtf, linear)
    var(--animdel, 0s)
    var(--animic, infinite)
    var(--animdir, alternate)
    var(--animfm, none)
    var(--animps, running);
}
Copy after login

Through custom properties, we can control all aspects of the animation. The advantage of CSS custom properties is that they can be read and set in CSS and JavaScript, and can reduce the amount of CSS code.

The animation itself uses a class selector and updates the variables in the [data-animation] selector:

 /* Animation class*/
.a-pulse {
  --animn: pulse;
}
.a-slide {
  --animdur: 3s;
  --animn: slide;
}

/* Keyframe*/
@keyframes pulse {
  /* ... */
}
@keyframes slide {
  /* ... */
}
Copy after login

Example: Use checkbox trick to pause animation

Create a checkbox to control pauses for all animations:

<input type="checkbox" id="data-animation-pause">
Copy after login
 [data-animation-pause]:checked ~ [data-animation] {
  --animps: paused;
}
Copy after login

Click the check box to pause/play all animations without JavaScript.

CSS-only slideshow

I use<details></details> Tags create a slide that automatically switches the slides through the active animation autoplay , each slide has its own secondary animation. The --animps attribute controls the playback status of the animation, --img-animps attribute controls the playback status of the secondary animation.

To prevent GPU overload, ideally, the main animation should pause all secondary animations. Chrome browser (currently) can update CSS custom properties from @keyframes animation.

Update --img-animps property in the main animation @keyframes :

 @keyframes autoplay {
  /* ... */
  51% { --img-animps: paused } /* Stop! */
  /* ... */
}
Copy after login

In order to be compatible with other browsers, the initial value needs to be set to running .

Enable prefers-reduced-motion

We can use prefers-reduced-motion media query to respond to user preferences:

 @media (prefers-reduced-motion) {
  [data-animation="alternate"] {
    --animdur: 4s;
    --animn: opacity;
  }
  /* ... */
}
Copy after login

Pause animation using JavaScript

We can use JavaScript to iterate through all [data-animation] elements and switch the --animps attribute:

 // ... JavaScript code...
Copy after login
Copy after login
Copy after login

Using IntersectionObserver

To automatically play and pause animations, we can use IntersectionObserver :

 // ... JavaScript code...
Copy after login
Copy after login
Copy after login

Add audio to the slide (Bonus)

Add an audio tag and control its playback and pause in JavaScript:

<audio src="your-audio.mp3"></audio>
Copy after login
 // ... JavaScript code...
Copy after login
Copy after login
Copy after login

Through the above methods, we can flexibly control the playback and pause of CSS animations, and improve page performance and accessibility.

The above is the detailed content of How to Play and Pause CSS Animations with CSS Custom Properties. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles