CSS: Add Icon to Links

By Xah Lee. Date: . Last updated: .

You can add a little icon to links to indicate what type of link it is.

For example, suppose you have links to Twitter like this:

<a href="https://twitter.com/xah_lee">Xah Lee</a>

And you want browser to show a icon, like this

CSS Google Plus Twitter Facebook icon link-2
Link with favicons, Twitter, Facebook, Google Plus

Instead of using a img tag for each link, you should use CSS to add them, by matching the URL.

Here's the CSS code:

a[href*="twitter.com/"] {
background:url(https://twitter.com/favicon.ico) no-repeat left center;

a[href*="facebook.com/"] {
background:url(https://www.facebook.com/favicon.ico) no-repeat left center;

a[href*="plus.google.com/"] {
background:url(https://ssl.gstatic.com/s2/oz/images/faviconr3.ico) no-repeat left center;
background-size:16px 16px;

You can do this to add a icon to any link to PDF file, or ZIP file, etc. Here's a example for Google Map and PDF file links:

a[href*="maps.google.com/"] {
background:url(https://maps.gstatic.com/mapfiles/maps-64.png) no-repeat left center;
background-size:22px 22px;

a[href$=".pdf"] {
background:url(http://example.com/i/pdf_icon.png) no-repeat left center;

Note: if you have lots HTTP request in your sitewide CSS file, it makes loading your page slow. There are 2 ways to avoid the multiple requests. One is to use a image sprite. Another way is to use CSS: Data URI Scheme, Base64 Encoding.

The CSS selector a[href*="twitter.com/"] matches any “a” tag with “href” attribute that has value contanining the string “twitter.com/”. For a full list of such selector syntax, see: CSS 3 Selector Syntax.

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.