Making Button Hover States Using a Spritesheet

fbsprite

The Problem

Using CSS image replacement to add hover and active states to buttons is good in theory. But this can be problematic because browsers typically don’t load images until they need it.

The net result is buttons that pop in or “blink” as you hover in click. A good solution to this is to use sprite sheets. This is a single image that contains your normal, hover, and active states. And with a little CSS work, you can position the image so only the state you want the user to see it shown.

The Markup

1
2
3
4
5
6
<div id="footerbuttons">
    <a href="javascript:;" class="fbicon">Facebook</a>
    <a href="javascript:;" class="ticon">Twitter</a>
    <a href="javascript:;" class="yticon">YouTube</a>
    <a href="javascript:;" class="rssicon">RSS</a>
</div>

The CSS

1
2
3
4
5
6
7
8
.fbicon {
    display:inline-block;
    width: 70px;
    height: 70px;
    background: url('../img/fbsprite.png') no-repeat;
    background-position:left center;
    text-indent: -99999px;
}

Using display:inline-block; with a defined width & height turns the element into a “window” that only shows the part of an image you want shown.

1
2
3
4
5
6
7
.fbicon:hover {
    background-position:center center;
}

.fbicon:active {
    background-position:right center;
}

Create :hover & :active states, and within those, change the background-position property to show the right part of the image. You can take this concept even further by positioning the image with pixels. This means you can do all your image replacement for buttons & icons with one file.

The Result

The buttons no longer blink when changing states, and the user is none the wiser. Shown above is an example of a sprite sheet. The first button is the normal state, then hover, then active.