Mike Morearty
06 Jun 2013

HTML+CSS to make an image “bounce” to a larger size on hover

Okay, in your HTML, you have an image, and you want to make it do a little animated “bounce” to a slightly larger size when the mouse hovers over it:

Here is the code to do that.

First, the HTML for five yellow stars in a row. As you can see, these are just empty anchor tags with a CSS class of star.

<a class="star"></a><a class="star"></a><a class="star"></a><a class="star"></a><a

Then, the CSS. The important thing is that we put the image in the background of the element (using CSS’s background-image). That way, when the background image changes size, it will not change the size of the element itself, and thus it will not cause the surrounding HTML to have to re-flow. The image is centered on the background of the element, and we are hard-coding its size to 15px:

.star {
    background-image: url(star.gif);
    background-size: 15px;
    background-repeat: no-repeat;
    background-position: center;

For good measure, we’ll also set background-clip property to be as big as possible, thus reducing the likelihood that, after growing, the background image might be clipped:

    background-clip: border-box;

Now let’s specify that whenever the background-size changes, we will animate the transition to the new size:

    transition: background-size 0.2s;

(Note, Safari will need -webkit-transition. Or just use Lea Verou’s -prefix-free script to avoid having to worry about prefixes.)

Now let’s make it bounce:

    transition-timing-function: cubic-bezier(.07,1.41,.82,1.41);

As for the numbers I am passing to cubic-bezier: I just played around with cubic-bezier.com until I found numbers I liked. (That site is also by Lea Verou. She is amazing.) If you like the animation but don’t want the bounce, just omit line transition-timing-function line.

Some extra CSS junk, and then close our tag:

    display: inline-block;
    width: 20px;
    height: 30px;
    text-decoration: none;
    cursor: pointer;

Finally, specify that when the user hovers over a star, the background-size should grow from 15 to 20:

.star:hover {
    background-size: 20px;

That’s it. You can see all the necessary code, and experiment with it, here.

comments powered by Disqus