I have an element that is red in resting state, and green when the user hovers their cursor over it. I have it set to ease the transition for 0.4s
.
Instead
you could use keyframes for this:
.element {
background-color: red;
height: 300px;
width: 300px;
}
.element:hover {
-webkit-animation: changeColor 0.4s forwards;
animation: changeColor 0.4s forwards;
}
@-webkit-keyframes changeColor{
0%{background: red;}
50%{background:yellow}
100%{background:green}
}
@keyframes changeColor{
0%{background: red;}
50%{background:yellow}
100%{background:green}
}
This works by adding the keyframe sequence when the element is hovered, and not during the actual element's creation (so the keyframes only work during the hovered stage).
The forwards
declaration is used so that the animation will 'pause' on the '100%' keyframe, rather than looping back and 'finishing where it started'. I.e. the first keyframe.
Please note: Other prefixes will need to be included see here for more info.