CSS animation-duration property


The animation-duration property in CSS specifies the length of time an animation takes to complete one cycle. It defines how long the entire animation process will last, from the start to the end of the animation sequence. This property is crucial for controlling the speed and timing of animations applied to elements.

Syntax

element { animation-duration: time; }
  • time: The duration of the animation. It can be specified in seconds (s) or milliseconds (ms). For example, 2s represents 2 seconds, and 500ms represents 500 milliseconds.

How It Works

  1. Define the Keyframes:

    • Create a @keyframes rule that defines the stages of the animation.
    @keyframes moveRight { from { transform: translateX(0); } to { transform: translateX(100px); } }
  2. Apply the Animation:

    • Use the animation-duration property to set how long the animation will take to complete.
    .animated-box { width: 100px; height: 100px; background-color: blue; animation-name: moveRight; animation-duration: 3s; }
    • This example will move the .animated-box element 100px to the right over a duration of 3 seconds.

Example

HTML

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Animation Duration Example</title> <style> @keyframes bounce { 0%, 20%, 50%, 80%, 100% { transform: translateY(0); } 40% { transform: translateY(-150px); } 60% { transform: translateY(-75px); } } .bouncing-box { width: 100px; height: 100px; background-color: red; animation-name: bounce; animation-duration: 2s; } </style> </head> <body> <div class="bouncing-box"></div> </body> </html>

Explanation:

  • @keyframes bounce:

    • Defines an animation named bounce that makes the element move up and down in a bouncing effect.
  • .bouncing-box:

    • The animation-name property applies the bounce animation to the element.
    • The animation-duration property is set to 2s, meaning the entire bouncing animation will complete in 2 seconds.

Important Points

  1. Units:

    • The animation-duration property accepts values in seconds (s) and milliseconds (ms). For longer animations, seconds are typically used, while milliseconds are used for more precise timing.
  2. Default Value:

    • The default value is 0s, which means if the animation-duration is not specified, the animation will not play.
  3. Multiple Animations:

    • If you apply multiple animations to an element, you need to specify the duration for each animation in a comma-separated list.
    element { animation-name: fadeIn, moveRight; animation-duration: 2s, 3s; }
    • In this case, the fadeIn animation will take 2 seconds, and the moveRight animation will take 3 seconds.
  4. Animation Timing:

    • Adjusting the animation-duration affects the overall timing of the animation. Shorter durations make the animation faster, while longer durations slow it down.