Grow your CSS skills. Land your dream job.

HTML for Icon Font Usage

Published by Chris Coyier

Where are we at right now in terms of the best markup for using icon fonts? Let's cover some options I think are currently the best.

  1. You want the icon to enhance a word
  2. You want the icon to stand alone but still be functional or informational

And our major goals here are:

  1. As good of semantics as we can get
  2. As little awkwardness for screen readers as possible

This ground has been treaded before, but I think the following techniques are a small step forward.

Enhancing a word

Let's say we have a header like "Stats" and we want to set it apart from other headers on the page and emphasize it's meaning. Semantic ideal:

<h2 id="stats" class="stats-title">Stats</h2>

Result:

So to get that icon in there (remember we're talking font icons here, we can't just pad the left and use a background) we'll need to insert some content.

Using a pseudo element is tempting because 1) they aren't read by most screen readers 2) we don't need dedicated markup for the icon which is a semantic ideal. Unfortunately, VoiceOver on OS X does read the content of pseudo elements. (reference 1, reference 2) Well, perhaps "fortunately" as if I'm reading the spec correctly that's what it is supposed to do. Pseudo elements just aren't in the DOM and thus that probably makes it harder for third-party apps to do.

The good news is that if we use a bit of markup, we can use aria-hidden attribute to prevent it from being spoken.

One more dash of bad news, even with aria-hidden on the markup surrounding the icon, VoiceOver on OS X will announce "HTML Content" when in focus. #dammit.

But alas! We can still win here. If we combine the markup technique and pseudo element technique, we can insert the icon with no VoiceOver weirdness. And as a double-win freebie, this combined technique is ideal for keeping our CSS lean and mean as it requires no class-name-bloat and works well with the next use case we need to cover.

So the final markup for this becomes:

<h2 id="stats">
  <span aria-hidden="true" data-icon="&#x21dd;"></span>
  Stats
</h2>

And the CSS is:

[data-icon]:before {
  font-family: icons; /* BYO icon font, mapped smartly */
  content: attr(data-icon);
  speak: none; /* Not to be trusted, but hey. */
}

Holy cow that's easy eh? Notice we aren't using a specific class name for the icon (e.g. like .icon-stats or something), we're using a data-* attribute to hold exactly which character we want to insert. In our icon font, we map those special characters to the icon we want to use. I find this perfectly semantic and even future proof (you could always select uniquely down the line even if you change the character). But if you prefer class names, more power to you, that's fine and doesn't change this technique drastically.

We'll cover mapping characters at the end.

Stand-Alone Icons

Say we have an icon that is a link or in some way functional, but it isn't accompanied by any text. For instance, a shopping cart icon that you can click to go to your shopping cart. Hopefully that functionality is obvious visually, with some kind of rollover state or general design obviousness. But that functionality also needs to be audibly obvious.

Instead of crafting a totally new technique to deal with this (which I've dabbled with in the past) let's lean on what we've already started. A span that inserts the character with a pseudo element, and text that sits right next to it that we kick off the page visually.

<a href="#rss" class="icon-alone">
  <span aria-hidden="true" data-icon="&#x25a8;"></span>
  <span class="screen-reader-text">RSS</span>
</a>

We need very little in additional CSS, just a little usability fix applied via class, and a toolbox class for hiding the text but leaving it accessible.

.icon-alone {
  display: inline-block; /* Fix for clickability issue in WebKit */
}
.screen-reader-text { /* Reusable, toolbox kind of class */
  position: absolute;
  top: -9999px;
  left: -9999px;
}

Hey, it works

View Demo

Update October 2012: I made a more proper demo comparing icon font usage with different techniques.

In VoiceOver, anyway. Would be great to hear from people who use other screen readers how this holds up.

Building / Mapping Your Icon Font

One "issue" in the world of icon fonts right now is that the majority of them available come pre-mapped to letters. Used with improper markup, the letters become "content" and a part of the semantics of the document. Or worse, read outloud by screen readers.

It almost never makes sense for an icon to be mapped to a letter. Instead, I recommend mapping icons to the closest unicode symbol you can find. For instance, mapping a heart icon to ❤ is a splendid idea. The meaning of symbols is rather relative anyway, so close counts and will be a semantic improvement immediately.

Even better, I like the idea of mapping icons to the "Private Use Area" of Unicode. As I understand it, this is exactly why it exists, to use for your own special characters. Mapped this way, you're in no danger of the character being spoken by a screen reader. Unfortunately at the time of this writing icons mapped this way don't work in even the latest Safari, so it's not yet recommended. Here's the scoop on the Private Use Area issues paraphrased from Keyamoon:

There is a difference between PUA (Private Use Area) and SPUA (Supplementary Private Use Area). The difference is explained a bit here. In my testing, PUA mapping works perfectly in all browsers. SPUA mapping borks in Safari only on Windows. The IcoMoon app only maps to PUA, which is recommendable at least for the short term future.

Here are the steps to follow:

  1. Pick out an icon font.
  2. Go to IcoMoon and load it up (or use their icon set)
  3. Choose the icons you want.

  4. Map them to the characters you want. Best to map to a relavant symbol or PUA.
  5. Download the fonts/demo.

You can also use Pictos Server to do the icon-picking and mapping, but it only works with Pictos and doesn't help you with choose symbols (you could copy and paste from here). It is a very nice set though and hosts for you and makes it very easy to existing sets without manually swapping out font files.

The Future

In the future, hopefully we can rely on speak: none; working perfectly everywhere so we can go back to using pseudo elements and perfect semantics.

Relevant

  • If you are worried about FOUT (Flash of Unstyled Text) that goes along with @font-face in Firefox 3.5/3.6 and IE 6-9, one solution would be to try FOUT-B-Gone.
  • Roundup of Icon Fonts

Comments

  1. Hey Chris, Thanks for this awesome read.

    I love your semantics, but never understand why you bother so much about screen readers. Do you have any stats about traffic from screen readers?

    • Peter

      I’d have to say it’s because you dont want to exclude anyone for any reason. It’s the same reason we all now must make mobile-first future-proofed responsive sites. So while your wordpress site may only get 1% mobile visitors now, that will increase. So much so that in the not-too-distant future, some folks may never own desktop computers and have their entire online experience through a mobile device…

      Oh yeah, and problem solving is fun.

    • In cases like this, the fact that the obvious/common solution “doesn’t work” points to a flaw in the solution: as Chris notes, the approach doesn’t actually work (the screenreader got it right: it’s just not what we wanted/expected).

      I can see why this would bug somebody, even if they didn’t care about screenreaders (not that we shouldn’t care about screenreaders).

    • One Web Accessible to everyone should be everyone goal #imho

    • Government sites yo…

      Most require some sort of 508 compliance, so even if they never get substantial traffic from screen readers they need accessibility standards.

    • Screen readers are another way for users to interact with the content on our sites. Apart from the clear accessibility implications, we should be writing our code so that it caters for all people regardless of how they access it ( keyboard, mobile etc)

    • Joeri

      Funnily enough, the things you do to optimize for screen readers are, in most cases, also good practice in general.

    • Bemused
      Permalink to comment#

      He bothers about screen readers because any website by a government or publicly funded institution such as a college or museum must have an accessible website. Here in Canada, the government is requesting that private business also make their websites accessible. It will mostly likely soon be law. So, why build a site and have to do it again as accessible? Why not just design it that way to begin with?

  2. Great topic, I always wanted to use font icons. You can do a lot of animations with them by only using CSS3

  3. Service itself looks very familiar. See OpenSource http://fontello.com/

    • Just for the record, I must say that the older version of my tool was available even before the pictos server. And it was the first to allow building custom icon fonts. You can look at the changelog page in my site.

    • Bookmarked :)

    • Vitaly

      And fontello’s generated fonts are hinted. That can matter for small sizes.

    • It would appear the Icomoon fonts are hinted against 16 and 32px sizes at least… See the text justification and page-type icons for the clearest example.

      Great article Chris!

  4. Great article.
    I tried the PUA technique with Icomoon on my website.

    It works fine on :
    - All IE on PC
    - Chrome on PC and Mac
    - Firefox on PC and Mac
    - Safari 5.1.2 on Mac
    - Mobile Chrome (Android) and mobile Safari (iOS)

    It doesn’t work on :
    - Safari 5.1.2 PC
    - Opera every platforms

  5. “Also, I’m sure eventually Safari will support PUA and we can map icons perfectly semantically as well.”

    Fingers crossed it happens soon. Great post. =)

  6. Chris love the article but i think the pros/cons of using a class name lean in the favor of using a class.

    data-icon="⇝" – looks clunky to me

    where as class="stats" – makes more sense

    <span aria-hidden="true" data-icon="⇝"></span>

    becomes
    <span aria-hidden="true" class="icon stats"></span>

    And

    [data-icon]:before {
    font-family: icons; /* BYO icon font, mapped smartly */
    content: attr(data-icon);
    speak: none; /* Not to be trusted, but hey. */
    }

    Becomes:

    .icon:before {
    font-family: icons; /* BYO icon font, mapped smartly */
    speak: none; /* Not to be trusted, but hey. */
    }
    .stat {
    content: ⇝;
    }
    /* List of other classes here */

    I realize there is a bit more CSS but this most likely will be created once in the CSS and implemented countless times through out the web site/app.

    #IMHO

    • James Peek

      I agree with Tom, much easier to be able to identify what the font is when reading through HTML when it has a class to identify it by rather than an obscure unicode character, plus it makes reuse cleaner as I don’t have to refer back to my unicode mapping.

    • I haven’t tried this yet. But I just wanted to add that I certainly prefer being able to define the content in the style sheet rather than in the HTML. As my CSS files are always external this allows me to manage and modify the icon info without touching the HTML pages. If I have an icon in a menu, for example, then I would have to change each HTML page (data-icon=) instead of just changing the CSS file.

      Many thanks!

  7. What a perfect timing! I’m in the middle of defining the front-end standards for icon usage in a project, and this post is a big help!

    The IcoMoon default CSS suggests the [class^="icon-"], [class*=" icon-"] selectors, which is a concern regarding browser performance. But the [data-icon] selector seems to work quite well (60ms increase).

    Nice, man!

  8. If you want to invite ie7 to the party you can put the character code right in the tag like: <i class=”ico”>& #xe826;</i>

  9. Great article, definitely have me some new things to think about on future sites. Thanks for your hard work.

  10. I think it’s a better idea to use a <b> element than a <span> element for inserting icons. The <b> element indicates that something is supposed to be stylistically offset, which an icon is.

    • Guy Routledge

      <i> is also now a stylistic element rather than one for adding <em>phasis and as icon starts with the letter <i>, I like to think of it as pseudo-symantic and often use it for coding up icons. Plus, it’s shorter to write than <span>.

  11. This speak:none; property sounds sexy as hell. Hope we can rely on it some days.

  12. At first I didn’t wasn’t sure how I felt about abstracting the class with a data-attribute like Tim, but the more I thought about parameterizing the CSS the more I love it!

    I work with a large app that uses dozens of icons; maintenance can be a real pain and implementation is harder for anyone not intimately familiar with the CSS. This solution would solve both of those problems — the stylesheet is terse, scalable and accessible.

    Great article, thanks for putting it together!

  13. You can also use ENTYPO font for this purpose.

  14. Why do screen readers read generated content in the first place? Shouldn’t their job be to read the content (markup) of the page? IMO, generated content should never be used for actual page content in the first place – CSS is for presentation, not content. Am I wrong to think screen readers are doing this wrong, and not developers?

  15. I’ve been using aria-label to markup my icon fonts. I haven’t tested in anything except Webkit, but it seems to read the same without the extra span.

    Here’s an example.

    <a href="http://twitter.com/genelocklin" class="icon-label" aria-label="Twitter" data-icon=""></a>

  16. Shazbot. I’m so used to saying that whatever it is “only works in Webkit”. What I meant was, I only tested it on VoiceOver.

  17. Chris,
    This is a great article, and I just used it to create some great buttons for a client. Being able to scale, adjust color, and otherwise control the aspects of the icons is very, very powerful. I was reluctant to try this before because I didn’t want to sacrifice accessibility, but now, with your help, I don’t have to worry.

    My client loved the fact that the icon moves a little on hover – I used a simple, quick transition for that. It is the little things that make a site so much more engaging.

    Thanks again!
    Also, thanks commenters and community – your thoughts and insights are greatly appreciated as well.

  18. Great links to those font-tools :)

    Didn’t we decide that -9999px was a bad idea, because of browsers having to render a 10000px+ container?

    Referring to this:

    .screen-reader-text { /* Reusable, toolbox kind of class */
    position: absolute;
    top: -9999px;
    left: -9999px;
    }

    Seems like perhaps it could be replaced by this:
    .hide-text {
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
    }

    http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

    For Compass users, there’s also useful stuff here:

    http://compass-style.org/reference/compass/typography/text/replacement/

    And if you swear to using sprites:

    http://compass-style.org/reference/compass/utilities/sprites/sprite_img/#mixin-sprite-replace-text-with-dimensions

    • I use H5BP’s visuallyhidden class:

      
      .visuallyhidden {
      	border: 0;
      	clip: rect(0 0 0 0); height: 1px;
      	margin: -1px;
      	overflow: hidden;
      	padding: 0;
      	position: absolute;
      	width: 1px;
      }
      
  19. John Cheesman

    Great article, I’m using Ico Moon app for a site I’m working on. I’m having trouble replacing the button on my search form with a suitable icon as I can’t nest spans inside it. Is there a way around this without positioning things on top of each other?

  20. tomasz86
    Permalink to comment#

    Frankly speaking, I dislike icon fonts very much. They are completely unsemantic. What’s more important, try to disable Web fonts in your browser and then view a website which uses such fonts. Letters or other completely unrelated characters will be displayed instead of those icons. This will happen also when for some reason the icon font hasn’t been downloaded (server problems, etc.).

    • This entire article is dedicated to those issues and explaining why none of those things you just said are true if you do it right.

    • Permalink to comment#

      @Chris

      I must admit that I probably used the wrong word to describe the problem. The code may be semantic but I’d argue that there exist at least several issues when it comes to accessibility.

      This article describes better what I’m trying to say:

      Icon font accessibility

      ACCESSIBILITY IS NOT (ONLY) ABOUT SCREEN READERS

      Most web developers who have heard about accessibility tend to think that accessible code is code that works decently in screen readers. Not quite. Screen readers are just one type of assistive technology (and more broadly one type of user agent). Some people will use other assistive technology, or they will use regular web browsers but use some of their features which we’re not used to design for.

      and this:

      The stylesheet is applied, but the font file is not loaded or delayed (network issue) or not recognized (support issue). The text label is hidden, and what is displayed is sometimes a Unicode symbol (if the user’s system fonts support it), and most of the time a meaningless letter like a capital “B” or a lowercase “z”.
      The user asked their browser to always use their preferred font (e.g. a font designed for dyslexics), overriding the page’s styles. What gets displayed is either a Unicode symbol or a meaningless letter.

      The article is from 2011 but these issues are still relevant. If you turn off Web fonts (IE9+ disables them if you turn on the Protected Mode!) or override the default font in the browser, a bunch of random letters / numbers gets displayed instead of the icons. This is exactly what happens here, at CSS-Tricks, and many other websites.

  21. hd7
    Permalink to comment#

    First, sorry I’m French, so I will try to write well…
    I am working on accessibility of font-icons, and so I have seen a lot of examples of your technique here. But, you add a markup in HTML with “aria-hidden” and “data-icon” attribute, and I would like not to have to insert a markup just to show icon. And so, can we simplify your technique, just by adding “data-icon” attribute to the” icon markup”, and to be sure that screen readers will not “see” it ? For example :

    <h2 data-icon="⇝">My title</h2>
    /* CSS */ h2:before { content:attr(data-icon); }
    
  22. James Donaldson
    Permalink to comment#

    Testing done by Filament group suggests some compatibility issues with Icon fonts with several browsers. Have you encountered these issues yourself at all in testing? For reference, here’s a compatibility chart they put together to compare to their Grunticon solution: https://docs.google.com/spreadsheet/ccc?key=0Ag5_yGvxpINRdHFYeUJPNnZMWUZKR2ItMEpRTXZPdUE#gid=0

  23. I just discovered this Icon Font thing when looking at the source code of a website. So I did a little search to learn more about them and even after reading this great post, I still don’t get this icon font thing exactly.

    Anyway, I’m going to play with Icon Fonts, Reading isn’t better than playing with these new things practically :)

    Thank you,
    Shyam Chathuranga.

  24. rpk
    Permalink to comment#

    Out of curiosity, why is on the stand-alone-icons solution only the -9999px image replacement solution working? i’ve tried the two latest additions listed here: the scott kellum method (the text is shown anyway) as well as the h5bp method (the text gets invisible but still takes its place) but both don’t work. :/ Is that fixable if you try to avoid the -9999px solution?

  25. Hey, a typo: “psuedo” instead of “pseudo”. ;)

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".