CSS Keyframe Animations: display vs. visibility

The Problem:

During development on a recent project I was tasked with creating some Front End animations for a web app. This application would present a user with a list within two tabs (the tabs will display the list by either A-Z or by Category). Within these tabs you can also filter the list, and this is where the animation exists. Items would disappear and reappear. Wanting greater control over the animation, compared to simple JQuery, I started finessing CSS animation.

I quickly ran into a problem. I found that the CSS animation would re-fire/re-paint when the tabbed content came back into view.

Example: Toggle between the tabs and note that the animation fires each time you return to “Tab #1”

Why was this happening? I double checked my keyframe statement. Made sure I was setting animation-fill-mode to “forwards” to prevent repeating the animation. After much research and testing, I came to the conclusion that it wasn’t the CSS animation, which meant that it had to be within the JQuery.

The only JQuery being used was for the tabs. The tabs were using .hide()/.show() to swap the tabbed content into view. ‘Under the hood’ .hide()/.show() is placing an inline style of “display: block” (.show()) and changing it to “display: none” (.hide()).


The Solution:

After some testing (changing .hide()/.show() to use visibility:hidden/visible) I found a solution that would hold the CSS animations state.

Corrected Example: (Feel free to hit “Rerun” in the lower right to re-trigger initial animation”)

Unbeknownst to me display: block/none will re-paint/re-animate css animations when switched. Using the visibility property will preserve the animation state. Note that you will need some additional styles to remove the space left by visibility:hidden by setting a max-width to zero and overflow to hidden.