Home / Add an icon before or after a link with CSS

Add an icon before or after a link with CSS

CSS has a matching syntax for selectors which makes it possible to match the filename extension at the end of an href. This makes it easy to add an icon which relates to the link before or after the text part of the link.

Matching the filename extension

This works in all modern browsers. It does not work in Internet Explorer 6 but that is becoming less relevent these days. If the browser does not support the matching syntax then it simply won't render the image or any of the associated styling so it won't break anything.

For example, to match all zip files add the following to your CSS file:

a[href$='.zip'] {
    /* styling goes here */
}

The $= makes the match at the end of the href part of the <a> tag.

Adding an image icon to the link

Simply add the necessary styling to add a background image aligned either to the left or right of the link, and then enough padding to the right or left respectively so the text doesn't go over the top of the image.

The doc/docx and xls/xlsx examples add the icon to the right of the text in the link and the pdf and zip examples to the left. Make sure the padding is at least the width of the image.

In the example presented below the images are 16px x 16px so a padding of 18px allows for a couple of pixels space between the text and the icon.

a[href$='.doc'], a[href$='.docx'] {
    background: transparent url(/images/content/icon_word.gif) center right no-repeat;
    padding-right: 18px;
}
a[href$='.xls'], a[href$='.xlsx'] {
    background: transparent url(/images/content/icon_excel.gif) center right no-repeat;
    padding-right: 18px;
}
a[href$='.pdf'] {
    background: transparent url(/images/content/icon_pdf.gif) center left no-repeat;
    padding-left: 18px;
}
a[href$='.zip'] {
    background: transparent url(/images/content/icon_zip.gif) center left no-repeat;
    padding-left: 18px;
}

Working example

Here's the above example working in action.