About Lesson
Animation Direction
The animation-direction
property in CSS determines whether an animation should play forwards, backwards, alternate between forwards and backwards, or alternate between forwards and backwards on each cycle. It controls the direction of the animation sequence.
Here are the possible values for the animation-direction
property:
normal
: The animation plays forwards from the beginning to the end (default behavior).reverse
: The animation plays backwards from the end to the beginning.alternate
: The animation plays forwards, then backwards, and repeats.alternate-reverse
: The animation plays backwards, then forwards, and repeats.
The animation-iteration-count
property specifies the number of times an animation cycle should be played before stopping. You can use a specific number (e.g., 3
), infinite
to make it repeat indefinitely, or initial
to use the default value.
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 Example</title>
<style>
.container {
display: flex;
justify-content: space-around;
}
.box {
width: 100px;
height: 100px;
background-color: teal;
margin: 20px;
animation-duration: 2s;
}
.box1 {
animation-name: move-right;
animation-direction: normal;
}
.box2 {
animation-name: move-left;
animation-direction: reverse;
}
.box3 {
animation-name: fade-in-out;
animation-direction: alternate;
}
.box4 {
animation-name: spin;
animation-direction: alternate-reverse;
}
@keyframes move-right {
0% {
transform: translateX(0);
}
100% {
transform: translateX(200px);
}
}
@keyframes move-left {
0% {
transform: translateX(200px);
}
100% {
transform: translateX(0);
}
}
@keyframes fade-in-out {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div class="container">
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
</div>
</body>
</html>
In this example:
- Each
<div>
with the class.box
represents an element that will be animated. - Each
.box
has a different animation name (move-right
,move-left
,fade-in-out
,spin
) and animation direction (normal
,reverse
,alternate
,alternate-reverse
). - The animations are defined using
@keyframes
rules with different effects (moving horizontally, fading in and out, spinning).