Reputation: 4578
It seems like I could create an empty DOM element containing the string, set the opacity to zero, display it, and get then measure the width of the element, but that seems really hack-y. I'm wondering if there's a better way. Any ideas?
EDIT: I need the width in pixels when rendered to the screen, not the number of characters :)
Upvotes: 2
Views: 128
Reputation: 11704
Do you mean the pixel width? No, there's no easy way to predict that in Javascript without having the browser render it. It depends so much on what font the browser has chosen, font size (which could be affected by inheritance if set with percentage or em), letter spacing, element padding, etc ad nauseum.
Your proposed solution of rendering it in the browser, even with zero opacity or visibility:hidden
(thanks commenters) is the best way I think.
Upvotes: 3