Question

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!

Was it helpful?

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top