CSS Tip: How to Dynamically Change Animation with CSS Variables

CSS Tip: How to Dynamically Change Animation with CSS Variables

ยท

2 min read

Table of contents

CSS variables are specific entities in CSS used for storing values. It's similar to the way variables work in programming languages. In this article, we'll be looking at how to dynamically change animations with CSS variables.

CSS variables can be defined in CSS using a --variable_name: value format and they can be accessed using the var() function, where the value is placed inside the var() function is the variable name.

body{
    css-property: var(--variable-name)
}

Where css-property represents any CSS property.
To declare them globally, they are assigned their values in the :root pseudo-class.

:root{
    --blue: blue;
}

body{
    background-color: var(--blue)
}

One neat thing about this is that you can assign it to your HTML tags via the style attribute and change how an animation is displayed or timed simply by assigning an --index variable to each tag.
Let's take a look at a simple example below:

Demo

In the example above, each section is assigned an index on the style attribute and that index increases by 0.5. We then use the calc() function on the first point of the animation to multiply that index with 3rem on the top position property. After doing this, we set the final animation to reset the top CSS property to 0 thereby creating an animation delay on each section based on their index.
Here's what the HTML Code looks like:

<section class="container" style="--index: 1"></section>
<section class="container" style="--index: 1.5"></section>
<section class="container" style="--index: 2"></section>
<section class="container" style="--index: 2.5"></section>
<section class="container" style="--index:3.5"></section>

And this is the CSS:


.container{
  display: inline-block;
  background-color: pink;
  width: 5rem;
  height: 5rem;
  margin: 1rem;
  position: relative;
  animation: fade-up 2s infinite;
}
@keyframes fade-up{
  0% {
    opacity: 0;
    /* index value is used here */
    top: calc(var(--index) * 3rem);
  }
  100%{
    opacity: 1;
    top: 0;
  }
}

Did you use this style differently or do you have a demo you'd like to share on this? Let me know in the comments below!

ย