Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is div height calculated from font size

Tags:

html

css

Is there is a way to calculate automatic div height knowing contained font size and family? How does browser calculate this? Example:

<div style="font-size: 14px; font-family: courier">Text</div>

Above div height will be 16px; for "font-family: times" it will be 17px.

like image 532
Alexey Berezkin Avatar asked Mar 12 '23 00:03

Alexey Berezkin


1 Answers

I'm afraid the answer to your question is that it isn't straightforward.

For proportional fonts, the line height is either

  • the value of the line-height property if it's set in absolute lengths.
    <div style="line-height:20px">Text</div> will be 20px high

  • or the value of the line-height property multiplied by the font-size property if the line-height is a unitless value.
    <div style="line-height:1.5; font-size:14px">Text</div> will be 21px high

  • or some value chosen by the browser if line-height is set to its default value of normal.
    <div style="font-size: 14px;">Text</div> will usually be around 17px high, but this may vary among browsers and/or fonts

With monospace fonts however, like "Courier" in your example, the calculation depends on the browser and the browser settings.
Many browsers use a smaller size than the font-size for monospace fonts. This is a historical convention. How much smaller exactly, the convention doesn't say.
So with monospace fonts, all bets are off. Sorry!

like image 132
Mr Lister Avatar answered Mar 20 '23 14:03

Mr Lister