Exploring the use of animation-direction: reverse
to streamline my CSS keyframe animation process. An interesting scenario arises when a container div is clicked, toggling an "active" class using jQuery to trigger the animation in either forward or backward direction based on the class state. Both animations are essentially the same, with only the order of keyframes reversed. Initially, I expected that setting animation-direction: reverse
would simplify this by allowing one animation to be reversed for the other, but it doesn't seem to function as anticipated.
To view the codepen example without utilizing animation-direction: reverse
, click the link below:
https://codepen.io/soultrust/pen/gogKjN
The current markup and Sass CSS code snippet demonstrate how the animation works without reversing.
<div class="container">
<div class="line"></div>
</div>
$width-height: 100px;
$duration: 1s;
$line-width: 10%;
$animation-distance: $width-height * .45;
@keyframes line-in {
0% { transform: translateY(-$animation-distance); }
50% { transform: translateY(0); }
100% { transform: rotate(-135deg); }
}
@keyframes line-out {
0% { transform: rotate(-135deg); }
50% { transform: translateY(0); }
100% { transform: translateY(-$animation-distance); }
}
.container {
margin: 10rem auto 0;
width: $width-height;
height: $width-height;
position: relative;
border: 1px solid black;
&.active {
.line {
animation-name: line-in;
animation-direction: normal;
}
}
}
.line {
width: 100%;
height: $line-width;
position: absolute;
top: 45%;
background-color: orange;
animation-direction: normal;
animation-name: line-out;
animation-duration: $duration;
animation-fill-mode: forwards;
}
Upon changing the "active" animation as below, both directions of animations cease functioning:
&.active {
.line {
animation-name: line-out;
animation-direction: reverse;
}
}
It seems the issue lies in using the same animation, as manually setting animation-direction: reverse
paired with animation-name: line-in
effectively triggers the reversal of the line-in animation.