Eschon
Eschon

Reputation: 538

CSS3 animation when hover ends

I have a div with some images in it. When I move the mouse over one of the images, I want it to grow, when I move the mouse out I want it to shrink again. I know that there isn't a mouseout ore something like that in CSS, so I put the reverse animation into the normal style of the images. Now my problem is, that when I load the site all images do the shrinking animation.

Is there a way to do this only with CSS or do I have to use Javascript?

My HTML:

<div id="picmen">
    <img src="/images/b1.png" />
    <img src="/images/b2.png" />
    <img src="/images/b3.png" />
    <img src="/images/b4.png" />
    <img src="/images/b5.png" />
    <img src="/images/b6.png" />
    <img src="/images/b7.png" />
</div>

My CSS:

#picmen img {
    float: right;
    margin: 3px 1px 3px 1px;
    height: 50px;
    width: 50px;
    animation: shrink 0.5s;
}

@keyframes shrink {
    from{ width: 60px; height: 60px; }
    to{ width: 50px; height: 50px; }
}

#picmen img:hover {
    animation: grow 0.5s; 
    width: 60px;
    height: 60px;
}

@keyframes grow {
    from{ width: 50px; height: 50px; }
    to{ width: 60px; height: 60px; }
}

Upvotes: 3

Views: 1624

Answers (1)

Enigmadan
Enigmadan

Reputation: 3408

Try using:

transition-duration: 0.5s;

instead of creating @keyframe animations.

Your code would look like:

#picmen img {
  float: right;
  margin: 3px 1px 3px 1px;
  height: 50px;
  width: 50px;
  transition-duration: 0.5s;
}

#picmen img:hover {
  transition-duration: 0.5s;
  width: 60px;
  height: 60px;
}

If you want to add easing, you can use:

transition-timing-function: ease-in-out;

More information about transition css3 can be found on the w3schools website.

See it in action.


Why it works:

When you define and use an @keyframe animation, your code will run the animation every time it is seen.
A browser will read your code like this:

#picmen img{  //define all images inside 'picmen' div
    ...    //all of the basics (float, margin)
    height:50px; //set height to 50px (iff no further instructions about height follow)
    width:50px;  //set width to 50px (iff no further instructions about width follow)
    animation: shrink 0.5s;  //run an animation called shrink for 0.5 seconds 
                             //every time this state is entered
        --run animation called 'shrink'--
            @keyframes shrink {  //defines 'shrink'
                from{ width: 60px; height: 60px; }  //redefines starting width and height
                to{ width: 50px; height: 50px; }  //defines ending width and height
            }
        --end animation--
}  //end image definition

transition, will only make those changes on (as the name suggests) transitions.
The first time your images are loaded, they don't go through any state changes, thus no transition.

Upvotes: 3

Related Questions