javascriptcssfontsembedded-fonts

How to calculate descender height in javascript?


My css has defined the font-family to cascade depending on what fonts are available:

.myfont { 
    text-transform: uppercase;
    font-family: Calibri, Arial, sans-serif;
    padding: 2em;
    background-color: red;
}

and, depending on what font is rendered, I would like to adjust the padding to appropriately center the all-caps text in the <sarcasm>beautiful</sarcasm> red background. Is there a good way to calculate the size of the font descender so that I can adjust the bottom padding accordingly?

Bonus points for solutions that also calculate the ascender height, cap height, and x-height.

Thanks in advance!


Solution

  • This is possible: use this library: baseline ratio, or typography.js Insert two spans into a container div, with 0px font size and a large font size like 100 or 2000, call getBoundingClientRect();, get difference in height, and divide by the bigger ones height. The 0 px font lies on the baseline. This gives baseline ratio, percentage of ascender and descender.