Skip to content

Instantly share code, notes, and snippets.

@mbeaty
Created October 5, 2011 08:54
Show Gist options
  • Save mbeaty/1263968 to your computer and use it in GitHub Desktop.
Save mbeaty/1263968 to your computer and use it in GitHub Desktop.
Pixel width of HTML text
An interesting approach I found (didn't invent) for determine the width of some text in an HTML document:
1) Wrap your text in a table td element:
<table><tr>
<td id="test">Some text you want to measure in pixels</td>
</tr></table>
2) Define CSS rules to reset all default/inherited table styles for the table in (1), so there is no extra padding, margin, border, etc that would affect the pixel calculation.
3) Using Javascript, get the DOM element for td element above and get it's offsetWidth property. This will be the width of the text in pixels (unaffected by font characteristics).
x = document.getElementById('test');
return x.offsetWidth;
Some possible issues:
* The td element size could be affected by a parent element (maybe?)
* Need to check browser support for the element.offsetWidth property
See: https://developer.mozilla.org/en/DOM/element.offsetWidth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment