How to calculate descender height in javascript?
Asked Answered
W

3

5

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!

Witha answered 16/4, 2012 at 19:10 Comment(2)
Probably better to use line-height (using a relative unit) rather than padding to account for that.Fungiform
In this particular case, this worked. Its just a little unsatisfying considering there should be a way to do this...Witha
S
4

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.

Symbolist answered 8/8, 2014 at 8:57 Comment(1)
when is the height of the span not 0 when the font-size is 0?Haldis
S
0

AFAIK that's not possible with JavaScript. You may be able to find out the used font, but not the font parameters.

So you will need to search for these parameters (e.g. in font libraries) and store them by-font so that you can look them up once you know the used font.

Salim answered 16/4, 2012 at 19:20 Comment(0)
T
0

A web dev agency called EightShapes have put together a tool that lets you generate CSS to crop away the space above and below text and so make layouts that work well around ascenders and descenders. There's an accompanying blog post about it.

Trug answered 15/5, 2019 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.