Icons as backgrounds on anchors

Abstract

Following a discussion in UNWA about placing icons next to links for content in different formats, one possible solution is below. It uses a background image for the anchor, with a class on the anchor to know which background to put in. It then adds a padding to the left, just slightly bigger than the image, to move the hypertext out of the way. Text that follows hypertext flows as per normal.

Example

This line contains some text and links. See the information in PDF, Word or even Excel formats.

Code Used

  1. <p>This line contains some text and links. See the information in <a href="#" title="Information in PDF" class="pdf">PDF</a>, <a href="#" title="Information in MS Word" class="word">Word</a> or even <a href="#" title="Information in MS Excel" class="excel">Excel</a> formats.</p>
  1. a.pdf {
  2. background: url(/images/pdf.gif) no-repeat left center;
  3. padding-left: 20px;
  4. }
  5. a.word {
  6. background: url(/images/word.jpg) no-repeat left center;
  7. padding-left: 20px;
  8. }
  9. a.excel {
  10. background: url(/images/excel.gif) no-repeat left center;
  11. padding-left: 20px;
  12. }

Conclusion

An elegant solution, that degrades gracefully (those that don’t support CSS/have CSS enabled still see the normal text), works well/degrades well in IE6, IE7, Opera 8.54, FF1.5, Lynx and even Netscape 4, uses less code than other solutions, is easy to re-use, and overall a good example of CSS enhancing the experience for those that use/support it.

Minor Drawbacks

One drawback is that those with images disabled, but CSS enabled will see a gap where the icon should be. A second drawback is that the background image does not scale with the text, if resized within the browser. Both I would consider acceptable given the advantages it has over other solutions.

Tags