Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color for some seconds using only CSS

Tags:

css

Is it possible to change the color of a div on hover for X seconds, then return to its original color using only CSS?

I do not want any fade ins or outs between the color. For example, if I want to change the color of the div to yellow for 1 second on hover, it must remain yellow for 1 second, then immediately return to the original color.

This (http://jsfiddle.net/hZ49y/1/) is what I have so far. It works as I described above, but I feel that this way of using animation is not intuitive and hard to understand. Should I stick to using JavaScript for this purpose? What are some alternatives?

like image 642
CookieEater Avatar asked Jan 14 '14 12:01

CookieEater


1 Answers

It is possible, but requires some math!

Here is the Fiddle

You must use another parameter of animation: animation-iteration-count as 1

div:hover {
    animation: myfirst 2s 1;
}

@keyframes myfirst
{
    0%      {background:red;}
    25%     {background:yellow;}
    75%     {background:yellow;}
    100%    {background:red;}
}

This is going to perform a 4s animation with the following "key-frames":

0s > red
1s > yellow (stays 2 seconds here)
3s > yellow
4s > red

The only problem is that the animation stops on mouse out. But you can use javascript to activate the animation (by toggle a class), so the animation doesn't stops on mouse out.


Update:

Here is a Fiddle with js to control css animation.

like image 89
António Almeida Avatar answered Oct 23 '22 00:10

António Almeida