Passa al contingut principal

HTML for Icon Font Usage

HTML for Icon Font Usage:
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. Psuedo 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
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.
HTML for Icon Font Usage is a post from CSS-Tricks

Comentaris

Entrades populars d'aquest blog

10 alternativas a Cuevana para ver películas online

10 alternativas a Cuevana para ver películas online : Durante este último tiempo, en Cuevana se sucedieron varios “problemas” por los cuales hubo que ajustar algunas cosas antes de tiempo (como el rediseño del sitio), que dejaron a algunos usuarios ciertos problemas para acceder a las películas o series del portal. Pero realmente esto es algo que no incumbe a los usuarios y, como sabemos, existen muchas otras alternativas a Cuevana dando vueltas por Internet, que intentaremos presentar aquí mismo. Los sitios que repasaremos funcionan del mismo modo que Cuevana, mediante la instalación de un plugin que permite visualizar los videos de Megaupload o WUShare, entre otros servicios, en una calidad de imágen realmente excelente. Tal como sucede con el más popular servicio, todos ellos tienen publicidad que en algunos casos resulta insoportable, pero como dice Federico en DotPod “a caballo regalado no se le miran los dientes”. Alternativas a Cuevana 1. Moviezet Posiblemente el mejor clon d...

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

Más de 50 de las mejores herramientas online para profesores

No es una exageración afirmar que hay ciento de aplicaciones educativas por ahí por la red, para todos los gustos y de todos los colores, por lo que es difícil tratar de recogerlas todas en un listado. Sin embargo, algunas destacan más que otras por su innovación y por su capacidad para conseguir adeptos, y esas son las que protagonizan la presente recopilación. Son 50 interesantes herramientas online basadas en las recopilaciones de EduArea , las muchas ya tratadas en Wwwhat’s new y las destacadas por la experiencia. 1. Dropbox : Un disco duro virtual con varios GB gratuitos y al que se accede desde casi cualquier dispositivo. Sin embargo, es muchísimo más que eso, de hecho ya comentamos 20 razones . 2. Google Drive : La evolución de Google Docs que suma a sus múltiples herramientas de creación de documentos, un considerable espacio virtual gratuito. 3. CloudMagic : Una extensión y una app multidispositivo para buscar información simultáneamente en Gmail, Twitter, Facebook, Evernote ...