Home / Add an offsite link icon after external links with CSS

Add an offsite link icon after external links with CSS

It can be useful to have an offsite link icon next to external links on a web page. This is easy to implement using CSS without having to add any additional elements to your anchor tags or additional image tags to the HTML source.

An example of an offsite link with the external image is like this (if you are reading this in a feed reader and the icon doesn’t appear after the text please click through to this article to view it in a web browser):

Link

The most obvious way to do something like this with HTML and CSS is like this.

CSS:

a.external {
    background: url(/images/external.png) center right no-repeat;
    padding-right: 13px;
}

HTML:

<a href="#" class="external">Link</a>

However this solution requires you make sure you always put class="external" in your <a> tags, which is easy enough to forget to do. Instead you can use a little bit of CSS magic like so:

a[href^="http://"] {
    background: url(/images/external.png) center right no-repeat;
    padding-right: 13px;
}

This will now make all links in the web page that start with http:// have the external link icon.

There are two catches with this:

1) Any links to your own website that start with http:// and contain you own domain name will have the external link icon. The only way I could figure out how to get around this was to have a rule matching links that start with http:// and the website’s domain to set the background and padding back to the defaults.

For example, to do this for my blog you’d do this:

a[href^="https://electrictoolbox.com"]  {
    background: none;
    padding-right: 0;
}

2) It won’t work in Internet Explorer 6. But then maybe you don’t care, and the market share of IE6 is dropping day by day and will finally disappear forever. The worst case is that they simply won’t see the icon so it’s not really a big deal.

It’s also possible to do this with Javascript which can act as a fallback to make it work for Internet Explorer 6. I’ll show how to do this tomorrow using jQuery.