Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between a font-size and how many pixels a character actually takes up on screen?

Tags:

html

css

fonts

I am building a specialized UI where I need to know exactly how many pixels are occupied by some string.

I've been trying to set the character size with the font-size property. But the relationship between font-size and the width of the div is not what I'd expect. For instance, here is a div with three characters each sized at 25px. As you can see, the text does not fill the 75px of the div.

<div style="font-size:25px; width:75px; background-color:green">Dog</div>
  1. What's going on?
  2. I'm looking for some way to make sure dog fits really snugly into its div. Any suggestions?

Thanks!

enter image description here

like image 663
bernie2436 Avatar asked Nov 13 '15 02:11

bernie2436


2 Answers

font-size controls the height of characters, not the width: letters in proportional fonts each have a different width, appropriate for the letter (usual example is "W" and "i"). If you want each character to take up the same width, use a monospaced font instead. These are generally less comfortable to read when used for a lot of text (they're fine for words).

Depending on what font renderer is used by a given browser, even fonts rendered at a particular pixel size may look slightly different on different browsers (or different operating systems running the same browser). This applies to monospaced fonts, too.

I'd strongly advise against relying on exact pixel-size measurements for any kind of UI, unless you generate bitmaps instead of using fonts so you know exactly what size to expect. (Consider what happens to the UI when a user tries to change the font size to make the text more readable. A given font size may not fit all readers. Another example is words of varying length: if you autofit words to the UI, short words will be big, long words will be tiny.)

If you work with actual text (rather than pregenerated images), I'd design the UI as much as possible to be flexible and able to deal with most variations in pixel size / screen resolution / zoom / etc.

For more details, read this article.

like image 140
xxbbcc Avatar answered Nov 22 '22 07:11

xxbbcc


Your best bet is to keep adjusting the font size until it fits the space you want if it's really that important for the word to be that width. I'm an Artist primarily and I do a lot of typefacing so TRUST ME when I say that you DO NOT want all your letters to be the same size, it just doesn't flow properly, as pointed out in the other answer with W and i. Depending on the end results you may want to look at sizing your text with "vw" or "vh" instead of "px" or "pt", it helps it stay proportionate to the screen size the user is viewing your app on.

like image 21
Optiq Avatar answered Nov 22 '22 05:11

Optiq