Hans Sprecher

Subpixel Nav Icons

Hans Sprecher, @honzie

21.1.2013

Chris Coyier and Paul Irish blew my mind a month ago. In a beautiful one, two double punch of CSS wizardry, they introduced using subpixel rendering in animations for truly smooth experiences. This may be the coolest demo on the web since fixed background positions and a spiral shell (remember this article).

Chris and Paul lay out some reasons and good practices for CSS-based animations:

Each one of these points should make your jaw sink a little bit lower. CSS and JS are really awesome some of the time.

Subpixels and Navicons

Subpixels are pretty amazing things. They are what make our screen fonts really nice and crisp. Wikipedia has a pretty awesome article that has some decent visuals that really help put the concept together.

So, subpixels are great at smoothing fonts, but there are other UI elements that can benefit as well.

Smashing Magazine recently published an article on The Semantic, Responsive Navicon. The author talks about some different ways to render three bars in a row, which is a common navicon. The cleanest, simplest way is to use a Chinese Trigram symbol (☰). This has the benefit of being a single character to type in. However, it doesn't play nice with all devices, including Android phones.

Another solution is to use SVG in order to render the three lines. However, again, this can fail in mobile.

The author mentions using CSS, however points out that this can mutilate the lines at some different zoom levels.

Transform to the Rescue

This problem sounds familiar. On some displays or at some zoom levels, the absolutely positioned bars will shard in strange ways, like the left hand of this graphics:

In the left column, some bars become uneven because the elements have to snap to pixel grids. On the right hand side, the bars are roughly even, since they use subpixel rendering in order to maintain a constant height and properly scale without being constrained by the rigidity of the grid.

The reason they are rendered this way is because they are positioned with a CSS transform. Here is the code:

/* Navicon CSS */
.menu,
.menu::before,
.menu::after {
  width:20px;
  height:4px;
  background:#fff;
}

.menu {
  display:inline-block;
  position:relative;
}

.menu::before,
.menu::after {
  display:block;
  content:' ';
  -webkit-transform:translateY(-8px);
}

.menu::after {
  -webkit-transform:translateY(-`6px);
}

<!--Navicon HTML-->
Menu <span class="menu"></span>

A full demo is also available.

Of course, everything isn't perfect. The smallest of these icons on the right hand side shows an interesting width artifact. I prefer the width artifact to the uneveness of the absolutely positioned icon. However, before you launch a solution into the wild, you should make sure to test it on different devices and zoom levels and make sure it holds up.

Have further considerations about UI pieces that can be rendered well with subpixels? Drop a line to @honzie.