String length in pixels from font size

anonymous's picture

Is there a way to figure out how many pixels a string of characters takes up from it's font size?

Ie. what is the pixel width of "this string" in Arial 8pt?

komitlak's picture

if you map all the bitmaps of the characters at the given size, but that's LOT of work!


hrant's picture

You might consider using a monowidth font - that'll save you a lot of coding.

Otherwise you might use canned approximations of bitmap widths for "prototypical" glyphs (which does depend on point size though) - like take "i" to be three or four pixels. Arial would be a good source for these.


aluminum's picture

"I'm exploring some ways to get text to fit within a certain pixel width of an html table cell."

That's not how the web works. The best you can do is suggest a typeface at a certain size, but you need to accomodate the fact that anyone can change the typeface and size as they personally see fit.

If you're OK having text just 'disapear' then wrap the text in a fixed-sized div with overflow set to hidden.

anonymous's picture

Thanks for the replies.

I'm exploring some ways to get text to fit within a certain pixel width of an html table cell. Ideally I'd like truncate the text with an ellipses after a certain number of characters, so it wouldn't have to be 100% accurate... but I'd be okay with an html/css solution (which I'm also not having much luck with) that just makes the text go bye bye after x pixels.

Anyway, thanks again.

Thomas Phinney's picture

To get the width of a string set in a given font, you need:

- font size

- the font itself (advance widths at least)

- to know if kerning is on, and if so, account for it as well

- if it's TrueType (as Arial is), and you're looking at the hinted widths, you need to actually run the glyphs as programs to see whether the widths change

This assumes the text isn't justified and has nothing else to mess up its spacing....



Syndicate content Syndicate content