How to animate in CSS

A touch of CSS animation goes a long way in designing an immersive experience for visitors. The best animations can serve the content and user experience without distracting or appearing gimmicky. In this blog, we talk about how to animate in CSS with examples.

GraphQL has a role beyond API Query Language- being the backbone of application Integration
background Coditation

How to animate in CSS

Why use animations?

Being a front-end developer, creating a beautiful UI with a pleasing user experience is an important part of the job. Adding animations to a website contributes a lot towards this goal. It not only makes our website look good but also makes it stand out from the rest.
Animations play a critical role in improving the experience of users as they assist in providing improved visual feedback and help in making interactions with the website striking.
They are also a great way to highlight interactive elements and add interest and fun to the designs.

What is @keyframes?

Animation is basically changing a UI element’s style continuously over a period of time. In CSS, to assign a particular style to a particular time interval, we use the @keyframes rule.

Let’s start by creating a basic animation of a sliding box.

Sliding box animation - CSS

We will be using below HTML template throughout:



  <html> 
   <head> 
    <link rel="stylesheet" href="/src/styles.css" /> 
     <title> Parcel Sandbox </title> 
     <meta charset="UTF-8" /> 
    </head>
    
    <body> 
     <div id="app"> 
      <div class="container">
       <div class="box"> </div> 
      </div> 
     </div> 
    </body> 
  </html>


There are two ways to use this rule:

  1. From - to approach
  2. Percentage approach

Syntax:


@keyframes <animation-name> {
  from {
    <initial-css-properties>
  }

  to {
   <final-css-properties>
  }
}

The first thing to note is, <animation-name> can be any name you want to give to your animation. It can very well be like @keyframes myAnimationOfSliding. But, for the sake of relevance and simplicity, let us name our animation as slide
Inside our @keyframes rule, we provide the element’s style at the initial state and final state of its entire duration. In our case of a sliding box, the rule would look like this:


@keyframes slide {
  from {
    transform: translateX(0px);
  }

  to {
    transform: translateX(500px);
  }
}

Here, we are changing the X-axis position of our element from 0px to 500px.

We could very well write this in the percentage form like:


@keyframes slide {
  0% {
    transform: translateX(0px);
  }

  100% {
    transform: translateX(500px);
  }
}

The benefit of using the percentage form is that you get more control over the timeline stages of your animation. If you want some different styles at say 50% of your animation duration, you can just add required styles in a similar manner like:


@keyframes slide {
  0% {
    transform: translateX(0px);
  }

  50% {
    transform: translateX(250px);
    background-color: blue;
  }

  100% {
    transform: translateX(500px);
  }
}

box class - animation in CSS

At this point, we have just created a new animation. But we still have not applied it to any element. To do that we use animation-name and animation-duration CSS properties. As the names suggest, animation-name tells our element which animation should be used and animation-duration tells how long the animation must last. Let’s add these to our box class which we have used in our HTML file.


.container {
  width: 600px;
  height: 100px;
  background-color: yellow;
  position: relative;
}
.box {
  height: 100px;
  width: 100px;
  background-color: red;
  animation-name: slide;
  animation-duration: 1s;
}

And there you have it, you have created your very first animation! 🎉🎉🎉

Now let us deep dive a little more and learn about various other animation properties we can use to make our animation a little more customizable.

Animation properties

animation-name

The name of the animation to be applied to an element.

animation-duration

It tells how long you want an animation’s timeline should be. It defaults to 0 seconds i.e. If you won’t provide any value to this property you won’t be seeing any animation on the screen. Also, it accepts only positive values.

animation-timing-function

This is used to control the speed of our animation throughout its timeline. CSS provides us with some ready-to-use values for controlling the animation speed:

1. Linear: The animation speed would be constant throughout the duration.

Linear - Animation in CSS

2. Ease: The speed would gradually increase till the middle of the animation, and would slow back down at the end. This is the default value used.

Ease - Animation in CSS

3. Ease-in: The speed would be slow at the start and will increase till end of the animation.

Ease in - Animation in CSS

4. Ease-out: The animation would start quickly at the beginning and slow down at the end.

Ease out - Animation in CSS

5. Ease-in-out: The animation would start slowly, speed up and then end slowly.

Ease-in-out - Animation in CSS

Besides these predefined values, if you want more control over the animation’s timing, you could use cubic-bezier(p1, p2, p3, p4) function to provide a custom time-speed curve. You can also use this super awesome curve generator to easily generate the values.

You can also use the steps(interval, jumpterm) function to control the speed in an interval-based style instead of using a curve-based approach.

Animation-delay

This defines the time to wait before starting the animation. Unlike the animation-duration property, you can define this as a negative value. If you set a negative value, the timeline in your @keyframes will start at that point. For example, if your animation is 10 seconds long and you set animation-delay to -5s, it will start halfway along your timeline.

Note: animation-delay only delays the animation once at the beginning. After that, the animation keeps on running continuously.

Animation-iteration-count

It defines the number of times the animation should run. By default, it is set to 1 i.e. the animation would run only once. This also accepts only positive values. You can provide infinite value to make the animation run in a loop.

Animation-direction

You can set the direction of running the keyframes by using this property. Below are the possible values:

  1. Normal: This is the default flow i.e. forward.
  2. Reverse: The animation would start from 100% and end at 0%
Reverse - Animation in CSS
  1. Alternate: This is a combination of normal and reverse. It will alternate between these two values over every animation cycle.
    0% - 100% -> 100% - 0% -> 0% - 100%
Alternate - Animation in CSS
  1. Alternate-reverse: This is similar to alternate. The only difference is, the animation would start from 100% and then keep on alternating over each cycle.
    100% - 0% ->0% - 100% ->100% - 0%
Alternate-reverse - Animation in CSS

Animation-fill-mode

If you remember, in our initial example of the sliding box, after the animation completes, it reverts back to its original state. But, in case you want to persist the state of animation, animation-fill-mode is used. It can take these below values:

  1. none: The default value. No state would be persisted.
  2. forwards: The last keyframe will persist, based on the animation direction.
  3. backwards: The first keyframe will persist, based on the animation direction.
  4. both: follows the rules for both forwards and backwards

Animation-play-state

It allows us to play/pause the animation. It takes running and paused as possible values. On resuming, the animation starts from the same state it was paused.
You can also use the shorthand notation to use these properties in one go instead of specifying each of them individually.

Shorthand syntax



animation: (animation-name) (animation-duration) (animation-timing-function) (animation-delay) (animation-iteration-count) (animation-direction) (animation-fill-mode) (animation-play-state);


Example:



.box {
animation-name: slide;
animation-duration: 3s;
animation-timing-function: ease-in;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: normal;
animation-fill-mode: forwards;
animation-play-state: running;
}

Can be re-written as:

.box {
	animation: slide 3s ease-in 2s infinite normal forwards running;
}


Animation Chaining

You can also apply multiple animations to an element by chaining them together. Just separate each animation with a comma in the CSS.

Example:



.box {
  height: 100px;
  width: 100px;
  background-color: red;
  animation: slide 3s infinite, color-change 3s infinite;
}

@keyframes slide {
  0% {
    transform: translateX(0px);
  }

  100% {
    transform: translateX(500px);
  }
}

@keyframes color-change {
  100% {
    background-color: blue;
  }
}


Silidng and color change animation in CSS

In the above example, we have chained together two animations - one for sliding and one for changing the background color.
Note that both animations start at the same time. If you want some animation to start at a later point, you can use animation-delay property.

Note: If multiple animations are changing the same property for an element, only the last animation would be effective as it would override the previous ones. For example, if “slide” and “rotate” animations are applied on the same element, only “rotate” would take effect (assuming it is last in order) as both animations are changing the “transform” property.

Solution: To overcome this issue, you can wrap the element in another div tag and apply one animation to it. This will prevent the animations from overriding each other. You can also use animation-delay property, as needed, to generate the desired effect.

Do check our next blog on how to animate in Tailwind.

Hi, I am Omkar Jadhav. I am a frontend developer with a passion for problem-solving and creating responsive and user-friendly web interfaces that deliver exceptional user experiences.

Want to receive update about our upcoming podcast?

Thanks for joining our newsletter.
Oops! Something went wrong.