CSS Animation Fill Mode

Ben Lu
Ben Lu
Jul 22, 2017 · 2 min read

CSS animations are fantastic, they’re efficient and they don’t require any javascript. Lets quickly reference these articles: https://css-tricks.com/snippets/css/keyframe-animation-syntax/, https://developer.mozilla.org/en-US/docs/Web/CSS/animation, and https://www.sitepoint.com/understanding-css-animation-fill-mode-property/

The one we care about is animation-fill-mode, which can be none (default), forwards, backwards or both. Its purpose is not immediately obvious and the sitepoint article is a great article which I read in 2015. However this quote got me at the time:

To be honest, I don’t really see a lot of practical use for the value backwards

It was notable because backwards was a really common use of fill mode for me. So lets explain what fill mode is in really basic terms and why backwards is so useful. Here’s a quick example before we continue.


Why animation-fill-mode?

If you leave it at none, then before or after your animation, the styles will be what is set outside of the animation. For example a fade in will immediately fade out.

animation-fill-mode: none

Default, only uses animation styles during the animation

animation-fill-mode: forwards

Uses animation styles after the animation

animation-fill-mode: backwards

Uses animation styles before the animation

animation-fill-mode: both

Both forwards and backwards

note:

This doesn’t affect styles defined in between (for example 50%) where they’ll animate back to the original style.

Why animation-fill-mode: backwards is great

Lets go back to our original example:

Obviously, opacity by default is 1, but because there’s a delay, the box will immediately be visible, before disappearing and reappearing. We have 3 options here:

  1. Set an opacity style to 0 initially and use animation-fill-mode: forwards
  2. animation-fill-mode: backwards (opacity is default 1, otherwise style = to)
  3. animation-fill-mode: both

Lets say, that you want to do something after your animation, perhaps a hover change, then if you pick option 1 or 3, then you can’t touch the opacity option. No other style can affect the opacity.

So, you only need backwards if you have a delay, but that’s pretty common, and it means you can still manipulate the styles after the animation.

Summary

  1. Fill mode removes control over styles, preferably use none, or if you have a delay, use backwards
  2. With a delay backwards gives animations full control up until they finish, then you have control over your styles
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade