Paulund

Maintain Last Keyframe Of CSS Animation

When using CSS animation you can set the keyframes of activities you want the animation to do. For example if you want an element to fade-in you would change the opacity of the element from 0 to 1.


.element
{
    animation: fadein ease-in 2s;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

This will run on the page load event and will last two seconds. The problem that you get with CSS animations is that once the animation is complete the element will be restored back to the original styling. If you are using the fadein animation like above your element will start off hidden then will appear because of the animation and then be hidden again as it take the original styling. To fade-in you want the last keyframe to be maintained and keep the opacity at 1. There is a CSS property called animation-fill-mode, this defines how elements are styled outside of the CSS animations. The values of the animation-fill-mode can be, none (default), forwards, backwards, or both. Forwards will extend the styles of the last keyframe and assign this to the element. Backwards will extend the styles of the first keyframe and assign this to the element. Both will extend both the first and the last keyframes and assign this to the element.

-webkit-animation-fill-mode:forwards;
-moz-animation-fill-mode:forwards;
animation-fill-mode:forwards;

To maintain the last keyframe of the fade-in animation add the animation-fill-mode to the element.


.element
{
    animation: fadein ease-in 2s;
    animation-fill-mode: forwards;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}