Better Email Links: Featuring CSS Attribute Selectors

Published by Chris Coyier

betteremaillinks.jpg

What is an CSS Attribute Selector?

CSS provides a way to style elements based specifically on attributes of the link, rather than the type of element alone. For example, you already know that you can style a header element:

h1 { color: blue; }

But you can actually get much more specific and style only header elements that have a title attribute:

h1[title] { color: blue; }

You can take it even further, and only style header elements that have specific values of attributes:

h1[title="Go Home"] { color: blue; } /* Has the exact value "Go Home" in the title attribute */
h1[title~="Go Home"] { color: red; }  /* Has the value "Go Home" somewhere in the title attribute */
h1[title^="Go Home"] {color: green; } /* Value of the title attribute starts with "Go Home" */

 

What is unique about Email Links?

An email link differs from all other links because it always begins with "mailto:", which is the command the browser uses to notify the operating system that the user wants to send an email to a specific email address with the default email program. We can use this similarity between links to our advantage, so that we can apply CSS styling to only email links.

Here is the rub:

a[href^="mailto"] { color: blue; }

That will target all links with an href that begins with "mailto".

 

Finishing the styling

Now that we have those links targeted, we can do more than just make them blue. We can also make use of another powerful CSS technique, the "content" property. The content property literally allows you to add content to page elements, even content that you have pulled right from it's own attributes! Using a psuedo-selector, you specify where you wanted the content added, before or after.

Let's get fancy and pull the title attribute from our links and append them after the link itself, on the links hover state:

a[href^="mailto"]:hover:after { content: attr(title); }

That will work, but it's going to append that text right after the link, so let's make sure the formatting looks good and add a little spacing and a > character to seperate the link from text that will be added on rollover:

a[href^="mailto"]:hover:after { content: " > " attr(title); }

Beautiful!
[VIEW EXAMPLE]

 

Why is this better?

  • Just listing the email address itself as the link doesn't imply "action". I think it's abrupt when you click a link and it launches your mail client without any warning.
  • By naming your link something like "Send Email" - you are implying that action
  • Best of both worlds, now you can name your link "Send Email", but also show the email address.
  • Forward-Enhancing (and backwords-compatible). This technique will only work in good modern browsers, but it degrades well. Older browsers will just see the link and it will work fine.