Ghost Thumbnails
In the typical HTML image gallery the need of having an IMG element for each thumbnail link is redundant and having a thumbnail file on disk for each linked image is, albeit small, a waste of resources.
This article describes a techique called Ghost Thumbnails which avoids cluttering your markup with superfluous IMG elements and requires just one thumbnail file, regardless the number of images you want to show in your gallery.
The Markup
Since we don't need an IMG element to display each thumbnail the markup for the image gallery will be a sequence of anchors. As one might expect each link when clicked will lead the viewer to the depicted image in thumbnail:
<a style="background-position: 0 -100px" href="P8190052.jpg">
<span>At the Park, again.</span>
</a>
Ignore the background-position style for now, we'll talk about it later. The extra SPAN tag
is there for extra styling flexibility. It's worth point out that link text should not be blank, since lacking of
any style information the browser will be able to show only the link text (think about text-only web browsers or
screen readers).
The CSS
The CSS for this technique is pretty straightforward:
#demo-gallery a:link, #demo-gallery a:visited,
#demo-gallery a:hover, #demo-gallery a:active {
width: 100px;
height: 100px;
display: block;
padding: 0;
margin: 5px 0;
background: transparent url(thumbnails.jpg) top left no-repeat;
}
#demo-gallery a span {display: none;}
No big suprises here, the CSS code makes each link a block-level element, in order to properly set its width and height equal the thumbnail size, wich in this case is 100×100 pixels. The last line is the most important one, since we set the background image for all the gallery links to the same value, as the image thumbnails are combined in a single file.
Finally on each anchor we use the background-position property mentioned earlier to
slide up the single background image. Since each image has a fixed height we can easily
figure out the offsets needed to show up each thumbnail in turn: 0px for the first, -100px for the second,
-200px for the third and so on.
And here there's the final result:
Once you have figured out the basics you can really go creative with styling and obtain more pleasant results.
Browser Compatibility
This tecnique has been successully tested with IE6/Win, Firefox 1.0.7 and Safari 2.0.1
References
A great read about the wonders of background-position is
A List Apart CSS Sprites.
— Andrea Peltrin, October 2005.