CSS: replacing links with images

Replacing links with images is easy with CSS. All we need to do is to use the CSS sprites technique to get the best performance with image loading. The rest simply relies on the negative vertical value of the background-position property to correctly position each image on each link. Let's start with a simple navigation menu:

<ul id="navigation">
 <li><a href="#" id="a">A</a></li>
 <li><a href="#" id="b">B</a></li>
 <li><a href="#" id="c">C</a></li>
 <li><a href="#" id="d">D</a></li>
 <li><a href="#" id="e">E</a></li>
 <li><a href="#" id="f">F</a></li>
 <li><a href="#" id="g">G</a></li>
</ul>

So we have seven links. We need an image sprite made up of seven images, like the following:

Each image approximately occupies a 58 x 58 pixels square. The global height of our sprite is 400 pixels. Here's the CSS code:

#navigation {
 width: 600px;
 height: 58px;
 margin: 1em;
 padding: 0;
 list-style: none;
}
#navigation li {
 float: left;
 width: 58px;
 height: 58px;
 margin-right: 1em;
}

#navigation a {
 float: left;
 display: block;
 text-indent: -1000em;
 width: 58px;
 height: 58px;
 background-image: url(multi-sprites.gif);
 background-repeat: no-repeat;
}

#navigation #a {
 background-position: 0 0;
}

#navigation #b {
 background-position: 0 -58px;
}

#navigation #c {
 background-position: 0 -116px;
}

#navigation #d {
 background-position: 0 -174px;
}

#navigation #e {
 background-position: 0 -232px;
}

#navigation #f {
 background-position: 0 -289px;
}

#navigation #g {
 background-position: 0 -342px;
}

To remove the text from each link we use negative text indentation after turning each link into a block-level element having its dimensions equal to our base square. Then we use a negative vertical value for the background-position property to associate each link to its image. Each negative value is given by the sum of the preceding value plus 58. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

3 thoughts on “CSS: replacing links with images”

  1. Hi !

    The outline is not really nice with Firefox.

    You can add this rule to correct the rendering :
    #navigation a {
    overflow: hidden;
    }

    See you,
    Thomas.

Leave a Reply

Note: Only a member of this blog may post a comment.