Indicate special links with CSS

CSS makes it easy to highlight special links across your entire site. For instance, many of our sites indicate when a link points to a PDF or external website by labeling it with a special icon.

In the bad old days, web developers added “(PDF)” to each and every PDF link in your site by hand. This is doable but tedious, especially if someone else is making changes to the site after you’ve finished building it. This is where CSS generated content comes in handy.

The :after psuedo-class can automatically add a string after every element it matches and style it distinctively:

a[href$=".pdf"]:after {
    content: " (PDF)";
    color: #000;

The $= is a special selector expression that matches the end of an attribute; a[href$=".pdf"] (the double-quotes are important, by the way) will only match anchors where the href attribute ends in “.pdf”. You can also add generated content :before a link, which behaves exactly as you’d expect.

Another trick is to indicate external links with a special icon, such as a diagonal arrow. The ^= selector matches attributes that begin with a certain string:

a[href^="http://"]:after, a[href^="https://"]:after {
    content: "�0a02197";

This time, the generated content is two Unicode characters: a non-breaking space and a northeast-pointing arrow. There are plenty of places to look up Unicode characters (and what browsers support them); I usually end up at after a Google search. Note that we’re applying the same content to http: and https: links; you might feel like treating those differently for your own reasons.

If you aren’t happy with the common Unicode characters, or you want to use one that isn’t widely supported, you’ll have to use a graphical icon. Fortunately, CSS can help us out here, too:

a[href^="mailto:"] {
    content: url(/images/icons/email.gif);

In this case, email.gif should be a tiny graphic about the same size as your typical font, say 12 to 16 pixels square. Keep it to as few colors as possible, make the background transparent and optimize it, and you can probably get it under 200 bytes of data.

Modern browsers support generated content using :before and :after pretty widely. IE7 is probably the most common browser which does not. If you’re worried about such browsers, Modernizr can detect whether generated content is supported in a particular browser using feature detection.Use it, and then you can create alternate CSS styles for those older browsers (special colors, italics, background images or colors, or whatever you like best).

Leave a Reply

Your email address will not be published. Required fields are marked *