Hyperlinks with icons

Posted on May 7th 2022 in CSS by Pim Debaere.

Hyperlinks with icons

Does your website have different types of hyperlinks – URLs, e-mail addresses, phone numbers … – and do you want to make it visually clear to your visitors where they will end up after clicking? Then there is a small but handy trick for this, namely adding icons.

Icons in HTML

The most common application is to simply add the icons to your hyperlink, in HTML (see below). Nothing wrong with that per se, but there is a good chance that one will be overlooked by accident. Another disadvantage is that, when you have many hyperlinks, the file size of your HTML will also increase significantly. We all know that larger files lead to longer download times, which can be detrimental to visitors.

1
2
3
4
<a href="mailto:info@example.com">
  <img src="img/email-icon.png" alt="E-mail" width="16" height="16" />
  E-mail
</a>
Fig. 1 – Adding an icon to a hyperlink using HTML.

For one icon, the above is certainly a suitable way, but suppose we display an address book with a lot of email addresses and phone numbers?

Icons in CSS

Then my preference quickly goes to CSS. With CSS you don't have to change anything on the existing hyperlinks, but you can still provide them all with an icon. An additional advantage is that you can also change the icon in one place, if the style of the website ever changes, for example.

Below is an example of how to add an icon with CSS.

1
2
3
a[href^="mailto:"]::before {
  content: url('img/email-icon.png');
}
Fig. 2 – Adding an icon to a hyperlink using CSS.

A brief explanation:

  • a[href^="mailto:"]: with this we select all a-elements (hyperlinks) that have as href (Hypertext REFerence, or destination) an address beginning with "mailto:";
  • ::before: with this we indicate that we will add content before the content of the selected elements;
  • content: url('…');: the actual content we want to add, here a reference to an image.

Similarly, you can also retrieve all phone numbers, with a[href^="tel:"]. If you prefer to see the icon after the text of the hyperlink, use the pseudo-selector ::after instead of ::before. And of course you can add more properties to the above piece of CSS, for example a margin between the icon and the actual content.

The icon becomes part of the text of the hyperlink, so from now on you can also click on the icon to execute the hyperlink. If that isn't convenient!

Potential danger

As just mentioned above, the icon is added to the text of the hyperlink. This has the potential danger that the icon can still be added at the end of a line, but the text will be on the next line. This looks rather strange visually and we'd rather have both lined up together, wouldn't we? No problem at all thanks to the white-space property!

1
2
3
a[href^="mailto:"] {
  white-space: nowrap;
}
Fig. 3 – Keep the email address and icon aligned together.

Hopefully the above tips have made your life a little easier again.