Skip to content

Instantly share code, notes, and snippets.

@mbeaty
Created October 5, 2011 08:29
Show Gist options
  • Save mbeaty/1263930 to your computer and use it in GitHub Desktop.
Save mbeaty/1263930 to your computer and use it in GitHub Desktop.
HTML text width to pixels
Source: http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript
HTML:
<div id="Test">
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>
CSS:
#Test
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
}
JavaScript (fragment):
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment