Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a css property after it has been @keyframe animated?

I'm fading in some buttons with @keyframe animation from opacity: 0 to opacity: 1.

div{
    opacity: 1;
    animation: fadeIn 1s forwards;    
    -webkit-animation: fadeIn 1s forwards;
}

@-webkit-keyframes fadeIn {
    0%{
        opacity: 0;
    }100%{
        opacity: 1;   
    }
}

@keyframes fadeIn {
    0%{
        opacity: 0;
    }100%{
        opacity: 1;   
    }
}

div:hover{
    opacity: .5 !important; /* THIS DOES NOT HAPPEN BECAUSE THE OPACITY WAS ANIMATED */
    color: red;
}

On :hover, I'd like to change the opacity to .5 but it appears that after a property is animated using @keyframe, it can't be changed.

Simple example: http://jsfiddle.net/Lzcedmuq/3/


PS: In the real web-app, I am also scaling the buttons in so the fix I need is more than just for opacity. I need to be able to change any property that has been animated. I can do it with JS hackery but I don't want to.

like image 322
narrowdesign Avatar asked Apr 17 '15 17:04

narrowdesign


People also ask

Which CSS properties Cannot be animated?

CSS properties that define animation parameters such as animation-direction and animation-name are not animatable because animating them would create complex recursive behavior.

What is the CSS 3 rule that allows for animations?

The @keyframes rule specifies the animation code. The animation is created by gradually changing from one set of CSS styles to another. During the animation, you can change the set of CSS styles many times.

How do I trigger an animation again in CSS?

The key to restarting a CSS animation is to set the animation-name of an animation to 'none' and then setting it back to the original animation. As you can see this requires two steps. One to switch it to a different animation and one to set it back.

Which CSS property is used to play animation again and again?

The animation-play-state CSS property sets whether an animation is running or paused.


2 Answers

Disable the animation as part of the hover state:

div:hover{
    opacity: .5;
    -webkit-animation: none;
    animation: none;
    color: red;
}

One issue with this is that the animation will restart when the hover ends.

like image 82
zzzzBov Avatar answered Nov 02 '22 04:11

zzzzBov


This fixed the problem

opacity: 0.5 !important;

I can't answer to why the browser doesn't allow changes to animated styles, but it must have a higher priority then any new specified styles... so with that in mind you can use the !important to force that style to take top priority.

Demo

like image 40
floor Avatar answered Nov 02 '22 03:11

floor