Hello subpixel world

February 6th, 2014. Tagged: browsers, CSS, JavaScript

Since IE9 and Firefox(v.?) we now have subpixel rendering of fonts. This is cool and all but imagine this:

  • you have some text
  • you want to measure the width of the text and size another element to the same dimensions

Simple.

But if you use offsetWidth/offsetHeight to measure, you get a rounded integer and not the exact dimensions.

See this example.

In Firefox:

sub-ff

In IE:

sub-ie

So sizing something based on the offsetWidth will result in the familiar "css is awesome" picture.

The solution is to use getComputedStyle() and then round up to make more space, like:

var w = Math.ceil(parseFloat(getComputedStyle(text).width)) + 'px';

In other words:

offsetWidth considered harmful

Side note: getComputedStyle() doesn't exist in old IEs, but these don't have subpixel rendering either. So something like:

var w = window.getComputedStyle
  ? Math.ceil(parseFloat(getComputedStyle(text).width)) + 'px'
  : text.offsetWidth + 'px';

More typing, but hey - sexy fonts!

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov