CSS animation-delay property
The animation-delay
property in CSS specifies the amount of time to wait before starting an animation. It allows you to set a delay between the moment the animation is applied to an element and when the animation actually begins. This can be useful for synchronizing animations or creating timed effects.
Syntax
element {
animation-delay: time;
}
time
: Defines the delay before the animation starts. It can be specified in seconds (s
) or milliseconds (ms
). For example,2s
represents a 2-second delay, and500ms
represents a 500-millisecond delay.
How It Works
Define the Keyframes:
- Create a
@keyframes
rule to define the stages of the animation.
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
- Create a
Apply the Animation:
- Use the
animation-delay
property to specify how long to wait before the animation starts.
.fade-in-box { width: 100px; height: 100px; background-color: blue; animation-name: fadeIn; animation-duration: 3s; animation-delay: 2s; }
- In this example, the
.fade-in-box
element will wait 2 seconds before starting thefadeIn
animation, which will then take 3 seconds to complete.
- Use the
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 Delay Example</title>
<style>
@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.sliding-box {
width: 100px;
height: 100px;
background-color: green;
position: relative;
animation-name: slideIn;
animation-duration: 3s;
animation-delay: 1s;
animation-fill-mode: both;
}
</style>
</head>
<body>
<div class="sliding-box"></div>
</body>
</html>
Explanation:
@keyframes slideIn
:- Defines an animation that moves the element from the left (
translateX(-100%)
) to its original position (translateX(0)
).
- Defines an animation that moves the element from the left (
.sliding-box
:- The
animation-name
property applies theslideIn
animation. - The
animation-duration
property sets the animation duration to 3 seconds. - The
animation-delay
property specifies a delay of 1 second before the animation starts. - The
animation-fill-mode: both
ensures that the element retains the styles from the animation’s start and end states.
- The
Important Points
Default Value:
- The default value for
animation-delay
is0s
, meaning the animation will start immediately.
- The default value for
Multiple Animations:
- You can specify different delays for multiple animations applied to the same element by separating them with commas.
element { animation-name: fadeIn, slideIn; animation-duration: 2s, 3s; animation-delay: 1s, 0s; }
- In this case, the first animation (
fadeIn
) will start with a 1-second delay, and the second animation (slideIn
) will start immediately.
Timing:
- The delay is counted from the moment the animation is applied to the element, not from the page load or element visibility.