Home > Web Front-end > CSS Tutorial > How to Reverse CSS Animations on Mouse Out Using @keyframes?

How to Reverse CSS Animations on Mouse Out Using @keyframes?

Susan Sarandon
Release: 2024-12-09 21:19:10
Original
595 people have browsed it

How to Reverse CSS Animations on Mouse Out Using @keyframes?

How to Implement Reverse Animation on Mouse Out after Hover

In web design, animations play a crucial role in enhancing user experience. One common scenario is hovering an element to trigger an animation, typically a rotation. However, reversing the animation on mouse out can prove challenging, especially when using CSS3's @keyframes.

Considering the provided CSS example, where on hover the element rotates 360 degrees, the goal is to have it rotate back to 0 degrees on mouse out. Using @keyframes animation, it appears the desired effect cannot be achieved.

The solution lies in understanding the animation-direction property. "To" represents the end state of the animation, while "from" specifies the starting state. By incorporating the "from" keyword in our @keyframes definitions, we can create the reverse animation:

@keyframes in {
    from: transform: rotate(0deg);
    to: transform: rotate(360deg);
}

@keyframes out {
    from: transform: rotate(360deg);
    to: transform: rotate(0deg);
}
Copy after login

Additionally, cross-browser compatibility can be ensured by using vendor prefixes:

@-webkit-keyframes in {
    ...
}

@-webkit-keyframes out {
    ...
}
Copy after login

To further enhance the animation, it's crucial to specify the animation-direction property:

.class {
    animation-direction: alternate;
}
Copy after login

This way, the animation will seamlessly transition from "in" to "out" when the mouse moves out of the element's boundary.

Implementing this approach results in a smooth and efficient reverse animation that responds to mouse movements precisely. Here's a demonstration:

http://jsfiddle.net/JjHNG/35/

The above is the detailed content of How to Reverse CSS Animations on Mouse Out Using @keyframes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template