Smoothly Reverting CSS Animations (2024)

Smoothly Reverting CSS Animations (1)

Hey there, you probably tried to animate some HTML elements in your time using transitions, transforms, and animations in the CSS. I tried the same, but one problem occurred when I animated something on hover.

For example, you can look at the theme switch button on this blog (it’s in the menu at the top if you’re on mobile):

Smoothly Reverting CSS Animations (2)

When I first added the button and the animation to it, I made a mistake. You can see the mistake below:

Smoothly Reverting CSS Animations (3)

The mistake I made can be easily overlooked. If you look closely, you can see when I start to hover over it, the animation starts, but as soon as I move the mouse away, it abruptly resets to its starting point. It might be a small detail, and most folks can miss this, but it annoyed me from the start. Imagine the code for the theme switch to be something like this:

.theme-switch:hover { transition: transform 2s ease-in-out; transform: rotate(360deg);}

It was all fine, and it made the sun spin using CSS rotate, but the rotation would suddenly reset once I moved the mouse away from the sun icon. Thankfully, there’s a simple solution for it. We need to put the transition rule to the general .theme-switch rule, not just the :hover rule.

.theme-switch { transition: transform 2s ease-in-out;}.theme-switch:hover { transform: rotate(360deg);}

Let’s see what we get when we moved the transition rule:

Smoothly Reverting CSS Animations (4)

If we try to hover and move our mouse away, it will revert smoothly using our transition rule. No more annoying abrupt reset of the animation, yay!

OK, this was fun and easy if you use CSS transitions, but what if you decide to go with the keyframe animations? Read on to find out.

Smoothly Reverting Keyframe Animation

First off, if you are looking into reverting a keyframe animation, did you try to reconsider the approach you are taking? If you did and you realized that there’s no chance in the world you could use a transition animation, then read on. But if you can achieve what you need with a simple transition, scroll back to the first part of this blog post.

OK, so you are stuck with some keyframes, and you want to revert them, let’s say, on hover. How do you achieve that? First off, the solution is pretty hard to do with just CSS and HTML, but there is a way.

For example, let’s say you have a sun icon that is constantly spinning like so:

Smoothly Reverting CSS Animations (5)

The code for it would look something like this:

.sun-icon { animation: in 4s linear 0s infinite normal;}@keyframes in { from { transform: rotate(0deg); } to { transform: rotate(360deg); }}

Here we use @keyframes, the CSS at-rule that defines intermediate steps in a CSS animation. It differs from using transition by giving you more control over what happens at certain points in the animation. We want the element affected by the animation to go from 0 degrees to 360 degrees, and we use the from to syntax of keyframes. We could’ve also put 0% 100% instead of from to. They are synonyms, pretty much.

And, finally, at the .sun-icon rule, we use the shorthand animation rule where we define the following:

  • in - the name of the animation
  • 4s - the duration of the animation
  • linear - the animation timing function
  • 0s - the animation delay (meaning our animation starts immediately since the delay is 0 seconds)
  • infinite - the iteration count of our animation (how many times the animation will play out)
  • normal - the direction of the animation (can also be reverse, which we will see later)Phew, that is a lot of occurrences of the animation word.

Now that we have that, we should be able to revert the animation somehow. How can we do it? You might think we can leverage the animation-direction and put it into reverse instead of normal. Well, if we do that, we have a jumping animation like so:

Smoothly Reverting CSS Animations (6)

We added this bit of code to achieve the above mentioned:

.sun-icon:hover { animation-direction: reverse;}

But that is obviously unwanted behavior. How else can we revert the animation?

We can add a little trick. We can wrap the sun icon into a container that will spin in reverse while hovering on it. It will look like this:

Smoothly Reverting CSS Animations (7)

This will be the HTML part:

<div class="sun-container"> <img class="sun-icon" src="sun.png" /></div>

And this the CSS part:

.sun-container { width: 128px; height: 128px; animation: in 2s linear 0s infinite reverse; animation-play-state: paused;}.sun-icon { animation: in 4s linear 0s infinite normal;}.sun-container:hover { animation-play-state: running;}@keyframes in { from { transform: rotate(0deg); } to { transform: rotate(360deg); }}

The container animation will run for 2 seconds (twice as fast as the sun icon animation, which runs for 4 seconds). Also, the container animation will start as paused, but it will run when we hover over the sun container element.

Other Ways To Revert Keyframe Animations

There are other ways to do it, but it will never be as smooth as the trick I showed you with both parent and child element spinning. There is a way to do it with JavaScript and playing around with keyframes in the CSS Tricks article.

The main problem with keyframe animations is that there is no way to track their progress. Once the animation starts, there is no browser API to let you figure out if the animation is at 46% of completion, for example. You can, potentially, setInterval and make it fire on every 10% of animation and mess with it there, but it is an unreliable solution.

Let me explain why the solution with setInterval (like the one in the CSS Tricks article I shared above) is unreliable. Imagine if the setInterval fires a bit late, and you presume you are at 10%, but you’re actually at 12% of the progress. If you change the animation, assuming you are still at 10%, you will get a slight jumping of the animation if you try to edit it. This brings us back to the similar problem we are trying to solve in the first place.

As we saw, we can’t utilize the animation-direction rule and just change it from normal to reverse and vice-versa. The animation resets every time you change that.

There is potentially one solution that might work, and that is with multiple animations. We can split one keyframe animation into multiple small ones and listen for animationend event. If you’re interested in this solution, consider subscribing to the newsletter and follow me on Twitter, where I will post more about this.

Think Before You Animate

We’ve gone through a couple of solutions to revert an animation, but we never went through the most important point - consider what you are trying to animate and how you are doing it. It probably doesn’t make sense to use keyframes to rotate an element in our examples. We can quickly achieve that with CSS transitions. I ended up using that approach on my blog in the end.

What I am trying to say is that maybe there is a more straightforward solution for you out there. You might avoid developing complex solutions and breaking your head trying to solve something. If you need to take the more complicated route, go ahead, nothing is stopping you. I showed a couple of ways here to choose and follow through.

But I hope this blog post is helpful to those with this kind of problem. It was fun to go through and figure out how to solve the keyframes part. I am sad that there isn’t a proper solution for this in the CSS spec, but I hope it is coming in the future.

If you like what you read and you think others will benefit from it, consider sharing it on Twitter blow:

Had troubles with reverting a CSS animation? Don't worry, I got youhttps://t.co/uRn6dvSMGF

— Nikola Đuza (@nikolalsvk) December 20, 2021

Also, I made my blog code open source, you can check it out on GitHub here.

Thanks for tuning it. Catch you in the next one. Cheers.

Smoothly Reverting CSS Animations (2024)

FAQs

How do I make CSS transitions smoother? ›

Specify the Speed Curve of the Transition

The transition-timing-function property specifies the speed curve of the transition effect. The transition-timing-function property can have the following values: ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)

How do you smooth keyframes in animation? ›

To quickly get smoother animation between keyframes, right-click and select Ease In or Ease Out. Twirl down the caret next to a property's stopwatch to reveal the keyframe graph. Adjust the bezier keyframe handles to affect the rate of change for selected keyframes.

How to make infinite animation smooth in CSS? ›

The key to creating an infinite animation in CSS is to use the animation-iteration-count property in CSS, which determines how many times the animation will play. By setting the value to infinite, the animation will continue to play indefinitely, creating a seamless and continuous effect.

How to optimize animations in CSS? ›

  1. 1 Use GPU Acceleration. When it comes to CSS animations, leveraging the Graphics Processing Unit (GPU) can lead to smoother transitions. ...
  2. 2 Optimize Paint Times. ...
  3. 3 Reduce Reflows. ...
  4. 4 Simplify Animations. ...
  5. 5 Use RequestAnimationFrame. ...
  6. 6 Test Across Devices. ...
  7. 7 Here's what else to consider.
May 9, 2024

How do I make animations move smoothly? ›

Utilize Easing

Easing, also known as 'slow in and slow out', is a technique where the animation starts and ends slowly, while the middle part is faster. This results in a more natural and smoother animation. Let's see why easing is so effective: Natural Movement: Easing mimics the way things move in the real world.

How do I make sure my transition is smooth? ›

How to Ensure Smooth Transitions Between Paragraphs and Sections of Your Essay
  1. Understand the Purpose of Transitions. ...
  2. Use Transition Words and Phrases. ...
  3. Employ Parallel Structure. ...
  4. Establish Clear Topic Sentences. ...
  5. Provide Transitional Paragraphs. ...
  6. Maintain Consistent Themes. ...
  7. Use Repetition and Synonyms. ...
  8. Revise and Edit Carefully.
May 6, 2024

How do animators make smooth animation? ›

Ensure consistent frame rates, use ease in and ease out for gradual acceleration/deceleration, maintain realistic physics, pay attention to timing, and incorporate subtle movements for a lifelike feel, Testing and refining your animations can help achieve a polished and natural look.

How many frames do you need for smooth animation? ›

The standard frame rate for animated videos is often 24 frames per second (fps), but it can vary based on the style and desired effect. Higher frame rates, like 30fps or 60fps, are common for smoother motion, especially in gaming or high-action sequences.

How do you animate perfectly? ›

The 12 Principles of Animation
  1. Squash & Stretch. Squash and stretch describe how an object changes shape in response to forces acting on it. ...
  2. Anticipation. ...
  3. Staging. ...
  4. Straight ahead vs. ...
  5. Follow Through & Overlapping Action. ...
  6. Slow in & Slow out. ...
  7. Arcs. ...
  8. Secondary Action.

How can I be good at CSS animation? ›

How to create high-performance CSS animations
  1. Browser compatibility.
  2. Move an element.
  3. Resize an element.
  4. Change an element's visibility.
  5. Avoid properties that trigger layout or paint.
  6. Force layer creation.
  7. Debug slow or glitchy animations. Check whether an animation triggers layout. Check for dropped frames. ...
  8. Conclusion.

Is CSS good for animation? ›

There are three key advantages to CSS animations over traditional script-driven animation techniques: They're easy to use for simple animations; you can create them without even having to know JavaScript. The animations run well, even under moderate system load. Simple animations can often perform poorly in JavaScript.

Does CSS animation slow down a website? ›

Leveraging animation libraries for their complex effects can inadvertently slow down your site. Before reaching for these comprehensive solutions, consider if simpler CSS animations or lightweight JavaScript libraries could achieve similar results more efficiently.

What triggers CSS animations? ›

CSS animations enable web elements to transition from one CSS style configuration to another. The browser can start defined animations on load, but event triggered CSS animations rely on adding and removing classes.

How do I make my animation more dynamic? ›

Another way to create more dynamic animations is to add motion and timing to your elements, making them move and change in relation to each other and to the viewer. Motion and timing can create a sense of rhythm, direction, speed, and energy in your animation, as well as convey emotions, messages, or actions.

How do I make background transition smooth in CSS? ›

Using CSS gradients: CSS gradients can be used to create smooth and seamless transitions between different colors. This can be used to create a variety of effects, such as a background that fades from one color to another, or a background that changes color as the user scrolls down the page.

How do you fix transitions in CSS? ›

CSS transitions let you decide which properties to animate (by listing them explicitly), when the animation will start (by setting a delay), how long the transition will last (by setting a duration), and how the transition will run (by defining an easing function, e.g., linearly or quick at the beginning, slow at the ...

How do you make a smooth scrolling effect in CSS? ›

Then apply basic CSS styling to your HTML elements to define their appearance, such as colors, fonts, and layout. After that use the CSS to add a smooth scrolling behavior to our webpage, to achive this functionality use the CSS property “scroll-behavior: smooth”.

How to make transform scale smooth in CSS? ›

CSS syntax example for scale

Don't forget to add a transition! Without applying transition, the element would abruptly change sizes. Add the transition to the parent selector (not the hover selector). To make the transition smooth on both hover-over/hover-off.

References

Top Articles
Top 50 Agile Interview Questions and Answers (2024)
Agile Testing Assessments: Practice Questions (2024)
The Machine 2023 Showtimes Near Habersham Hills Cinemas
# كشف تسربات المياه بجدة: أهمية وفوائد
Social Security Administration Lawton Photos
Die Reiseauskunft auf bahn.de - mit aktuellen Alternativen gut ans Ziel
Red Carpet Oil Change Blackstone
Dirty South Swag Review | BatDigest.com
Greater Keene Men's Softball
10000 Divided By 5
Married At First Sight Novel Serenity And Zachary Chapter 950
Leicht Perlig Biography
Round Yellow Adderall
Leccion 4 Lesson Test
Midlands Tech Beltline Campus Bookstore
Jailbase Milwaukee
Ihop Logopedia
Warped Pocket Dimension
Wsisd Calendar
Best Transmission Service Margate
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Brise Stocktwits
Layla Rides Codey
The Secret Powers Of Doodling
Minneapolis, MN Real Estate & Homes for Sale | realtor.com®
Cato's Dozen Crossword
Bustime B8
Monroe County Incidents
Minor Additions To The Bill Crossword
Shaw Funeral Home Vici Oklahoma
Mrballen Political Views
Camwhor*s Bypass 2022
Grave Digger Wynncraft
'I want to be the oldest Miss Universe winner - at 31'
Gargoyle Name Generator
Allina Akn Network
Traftarım 24
Showbiz Waxahachie Bowling Hours
A Man Called Otto Showtimes Near Carolina Mall Cinema
Smoque Break Rochester Indiana
Personapay/Glens Falls Hospital
Bonbast قیمت ارز
Why Did Anthony Domol Leave Fox 17
Best Drugstore Bronzers
The Hollis Co Layoffs
About Data | Weather Underground
Craigslist Westchester Free Stuff
Toothio Login
Akc Eo Tryouts 2022
Caldo Tlalpeño de Pollo: Sabor Mexicano - Paulina Cocina
Black Adam Showtimes Near Grand 18 - Winston-Salem
Lharkies
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5815

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.