Adding Extra Information to Hyperlinks using CSS3

The contents of this article may be out of date. It has been archived and will no longer be updated, comments are closed and the page is provided for reference purposes only.

A few days ago I was reading a blog article that had a link for an iPhone application in the text, nothing unusual there, so I clicked the link and iTunes started to load. When iTunes had loaded I was taken directly to the app store and the page specific to the app I was reading about. This got me thinking that it would have been nice to know I was going to be taken to iTunes before I had clicked the link. The author could have put a note in the text but this could well get tedious so I got to thinking of another solution and this is what I came up with this...

Using CSS3 it is possible to add content using attribute selectors. A common example of this is often seen in print style sheets where we want to show the URI for a link that we otherwise would not be able to follow on paper.

a:link:after, a:visited:after { content:" [" attr(href) "] "; }

Using a similar technique we can automatically append a note to the end of all hyperlinks that take the user to iTunes content.

a[href*="itunes.apple.com"]:link:after, [href*="itunes.apple.com"]:visited:after, a[href*="www.itunes.com"]:link:after, [href*="www.itunes.com"]:visited:after { content:" (link will open in iTunes) "; }

What we are doing here is looking for “itunes.apple.com” or “www.itunes.com” in any URI on our page. This is done using an asterisk after href to indicate we want to match this string. We then add the content ” (link will open in iTunes) “, note the spaces, after the matched links that have been visited or not.

It’s not only links to iTunes links that cause files to open with another application, PDF documents often open in another application as well. We can apply a similar rile to append text to the end of any link that is a PDF document using the following CSS:

a[href$=".pdf"]:link:after, [href$=".pdf"]:visited:after { content:" (.pdf) "; }

Lastly using the CSS3 attribute selector to match link elements whose href attribute value starts with the string “mailto:”. Here we can add style to links that will open your mail client.

a[href^="mailto:"]

Note that these advanced CSS3 selectors do not work in Internet Explorer at this time (2009).

This article was posted on 24 April 2009 in CSS

That's the end of this article. I hope you found it useful. If you're enjoyed this article why don't you have a look around the archives, where you can find some more tutorials, tips and general ramblings.