Open In App

How to define the duration of an animation takes to complete in CSS ?

Last Updated : 08 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

When designing a website, JavaScript is generally used to define behavior for the web pages. But there are ways, which help us to define certain behavior for the page using CSS. One such behavior is animation. CSS animations are the methods that help us to change the behavior and appearance of a web page without using JavaScript. They define the appearance of the elements for different time intervals, thus displaying an animation.

Defining duration of animation: To use a CSS animation, we need to define a time interval for which the CSS will display different appearances. To do this, we have an animation-duration property which sets the time interval that animation takes to complete one cycle. 

Syntax:

animation-duration: (time in seconds);

Below are the examples that illustrate the use of animation duration.

Example: We will now create a color-changing animation. Let’s first create our HTML file which will contain a text for which we want to apply an animation.

HTML




<!-- filename: index.html -->
<!DOCTYPE html>
<html lang="en" dir="ltr">
 
<head>
    <meta charset="utf-8">
    <title>Animation example</title>
    <!-- This line defines the css styles file to be used -->
    <link rel="stylesheet" href="css/style.css">
</head>
 
<body>
    <h1 id="mainh1">GeeksforGeeks</h1>
</body>
</html>


Now that our HTML file is ready, we can define our styles and animation in the CSS file. We will use animation-duration property which will change the color of our heading in 5 seconds for this example.

CSS code: Note that we have created a custom animation by the name ‘change’ here. To learn how to create a CSS animation, refer this article.

The main thing to notice here is that we have defined the duration for animation as 5 seconds. It means that the text color of the heading should change from green to red in 5 seconds.

CSS




/* filename: style.css */
#mainh1 {
    animation-name: change;
    animation-duration: 5s;
    animation-iteration-count: infinite;
}
 
@keyframes change {
    from {
        color: green;
    }
 
    to {
        color: red;
    }
}


Complete Code:

HTML




<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <style>
    #mainh1{
      animation-name: change;
      animation-duration: 5s;
      animation-iteration-count: infinite;
    }
 
    @keyframes change {
      from {
        color: green;
      }
      to {
        color: red;
      }
    }
  </style>
</head>
 
<body>
  <h1 id="mainh1">
    GeeksforGeeks
  </h1>
</body>
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads