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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

Programming Sass to Create Accessible Color Combinations Programming Sass to Create Accessible Color Combinations Apr 09, 2025 am 11:30 AM

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.

See all articles