I have animation on hover. I want to reset it to pre-hover state after 1 sec. Currently it is animating for 1 sec but stuck in the to
state of keyframe
. How to make it go to pre-hover state even without the mouseout
.
.box:hover {
--border-size: 3px;
--border-angle: 0turn;
background-image: conic-gradient(
from var(--border-angle),
#ebe7ee,
#d7d7ef 50%,
#fff
),
conic-gradient(from var(--border-angle), transparent 20%, #08f, #f03);
background-size: calc(100% - (var(--border-size) * 2))
calc(100% - (var(--border-size) * 2)),
cover;
background-position: center center;
background-repeat: no-repeat;
animation: bg-spin 1s linear forwards;
@keyframes bg-spin {
to {
--border-angle: 1turn;
}
}
}
@property --border-angle {
syntax: "<angle>";
inherits: true;
initial-value: 0turn;
}
<div class="box"></div>
3
Answers
Actually what @hëcalim said is correct,
backwards
is the required trick but to get it working I had to movebackground-image
inside@keyframes
so that it is present for0%
and not present for100%
Here is what the final css code looked like:
Just switch the forwards in your animation property by backwards.
Forwards maintains the ending state of the animation while backwards resets it like the beginning of the animation.
Maybe try this, you can use a combination of animation and transition properties. The animation property will handle the initial hover animation, and the transition property will handle the reset transition after the hover state ends. Here’s an updated version of your code:
In this code, I added a transition property to the .box class, specifying a transition for the background property with a duration of 1 second and an ease timing function. This will handle the reset effect after the hover state ends.
Also, I removed the @property –border-angle block as it’s not necessary for this case. The –border-angle variable is directly used in the .box class and within the @keyframes rule.
Now, when you hover over the .box, it will animate to the hover state, and when you move the mouse away, it should smoothly transition back to the pre-hover state.