Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 17 Mar, 2021
Geek Week

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 time interval for which the CSS will display different appearances. To do this, we have 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 illustrates 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.

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.

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :