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.
In Firefox:
In 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!