Automatically add images to links

Adding images to links on your website can be very useful, it is helpful for the ease of use and also adds attractive visuals to your site.


It is very simple to add images to any link, just add a background image to the anchor tag using CSS right? But what if you want to add images to not only external links but pdf’s, gif’s, png’s, word documents or email links?

You could add a class to every single instance of that type, but this is very tedious and you still have the possibility of forgetting many of them, especially if your site is fairly large.

The answer is to use CSS Attribute selectors.

[href$="end of href path"]

[href^="beginning of href path"]

So If you would like to add a small icon next to your link that downloads a word document you would use this line of code:

a[href$=".doc "]{ background:url('../images/word-icon.gif') no-repeat left;}

PDF:

a[href$=".pdf"]{background:url('../images/pdf-icon.gif') no-repeat left;}

For the external links you would use this line of code:

a[href^="http:"]{background:url('../images/external.gif') no-repeat left;}

Email addres:

a[href^="mailto:"]{background:url('../images/email.gif') no-repeat left;}

The result:

Mario’s Resume (Word Doc)

Mario’s Resume (PDF)

© 2010 M2Volt all rights reseved

back to top