Giant Peach Blog

Subscribe to RSS feed

CSS Link Icons – using CSS to automatically give your links a relevant icon. August 28th, 2009.

A really useful but little-know feature of CSS 2.1 is the [href] selector. It provides a very simple way of styling links. This can be very useful if you have a large list of files, for example in an Admin/Control panel. Find out how you can make these look good and more user-friendly.To demonstrate what I’m going on about, see the list of links below:

As you can see the links have different icons assigned to them dependant on the type of file they are linking to. So how is it done? Well obviously you can inspect the CSS using Firebug but here is a stripped back explanation.

Firstly I styled the links with relevant padding and gave them a generic background image. This is a nice fall-back for cases where the file type linked to isn’t recognised.

A
{
padding: 5px 0px 5px 40px;
text-decoration: none;
background-position: 0px 50%;
background-repeat: no-repeat;
background-image: url(../images/icons/genericIcon.gif);
}

The following selector uses $, which basically means ‘ends with’. So A[href$='.pdf'] applies its magic to any link pointing to .pdf file.

A[href$='.pdf']
{
background-image: url(../images/icons/pdfIcon.gif);
}

So to add an icon for Microsoft Word docs, you create/download a word doc icon and save it somewhere in your websites images folder and link to it as I have done below. Notice that i have used .doc and .docx. This is so newer (2007+) word documents are also picked up.

A[href$='.doc'], A[href$='.docx']
{
background-image: url(../images/icons/docIcon.gif);
}

So how have we used this? Well, as part of our Bespoke CMS, we have created a file manager where the user can upload various documents and images.
To make this easier to browse, we have given different file types different icons. Some file types are grouped together. For example, we wanted all video files to share one icon. So the following CSS gives avi, mpeg’s and mov’s the same ‘vid’ icon.

A[href$='.avi'], A[href$='.mov'], A[href$='.mpg'], A[href$='.mpeg']
{
background-image: url(../images/icons/vidIcon.gif);
}

This CSS works in most recent browsers (IE7+, FireFox) and also degrades gracefully in old and wafty browsers such as Internet Explorer 6. IE6 doesnt understand the selector so just ignores it. Hope you find this useful.

2 Comments

  1. Oooh, I didn’t know about this – I thought you were going to use classes but that’s pretty smart, as is the degradation.

    Thanks :)

    Comment by iamkeir — August 28, 2009 @ 1:08 pm
  2. [...] The rest is here: Giant Peach Design – Blog – CSS Link Icons – using CSS to automatically give your links a relevant… [...]

Leave a comment

handle

Get in touch

Thank you, your enquiry has been sent.