Home >Web Front-end >CSS Tutorial >How Can I Animate CSS Custom Properties to Sequentially Show/Hide Multiple Elements?

How Can I Animate CSS Custom Properties to Sequentially Show/Hide Multiple Elements?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 01:14:09489browse

How Can I Animate CSS Custom Properties to Sequentially Show/Hide Multiple Elements?

Animating CSS Custom Properties/Variables

Problem:

Animating multiple elements with CSS custom properties (variables) isn't working as expected. The desired outcome is for inner divs to appear and disappear in sequence using a variable to control opacity.

Solution:

CSS Properties with Custom Types:

Introduce a custom type for the variable using @property, which allows the browser to understand the variable's data type and enable gradual animation:

@property --opacity {
  syntax: '<number>';
  initial-value: 0;
  inherits: false;
}

Animation with Custom Property:

Use the custom property in the animation keyframes:

@keyframes fadeIn {
  50% {--opacity: 1}
}

html {
  animation: 2s fadeIn infinite;
  background: rgba(0 0 0 / var(--opacity));
}

In this example, the html element's background is animated from completely transparent to partially opaque based on the --opacity variable, which is gradually interpolated over time.

The above is the detailed content of How Can I Animate CSS Custom Properties to Sequentially Show/Hide Multiple Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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