0

I am trying to to calculate text width in px.

I will take a string from html, this string may contain some special characters as well (in this example just a hyphen), and make this string an html content of a div, and calculate string width.

But I am getting strange results.

If there is an better way to get text width, cross-browser!, please let me know.

I have made a fiddle:

http://jsfiddle.net/YaPcP/39/

Thank you!

Toniq
  • 4,492
  • 12
  • 50
  • 109

3 Answers3

1

<div> elements are set to span the width of their parent element, so changing the font size will have no effect on its actual width. Changing your <div> to a <span> should give you what you're looking for.

SenorAmor
  • 3,351
  • 16
  • 27
  • I edited original a little bit: http://jsfiddle.net/YaPcP/50/. The only problem is it doesnt give the same results in every browser. In IE9 it almost 10px off and in Opera like 30px off. – Toniq Feb 23 '12 at 04:09
1

Add float: left; to #holder

#holder which is the test container for width, is defaulting to width: auto;. In other words, it is spanning 100% of the browser window and giving you the mixed results.

You might consider adding white-space: nowrap; as well to #holder should it ever exceed the width of it's container.

Updated fiddle

shaunsantacruz
  • 8,903
  • 3
  • 19
  • 19
0

It may look nasty but gives you the width:

http://jsfiddle.net/adaz/YaPcP/43/

Adaz
  • 1,627
  • 12
  • 14