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!

4

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

I edited original a little bit: 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.
0

It may look nasty but gives you the width:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.