Question

Specify fallback font sizes in CSS?

Is there any way to specify different font sizes for fallback fonts in CSS? I want to do something like this (which obviously does not work):

div {
    font-family: "Arial Narrow", Arial, Helvetica, sans-serif;
    font-size: 20px, 18px, 18px, 18px;
}

The idea being that Arial Narrow would display at 20px if the user has it installed; if not, the browser would fall back to Arial at 18px, then Helvetica at 18px, etc.

Or, could I use JS to achieve a similar effect?

 21  8834  21
1 Jan 1970

Solution

 8

The @font-face size-adjust descriptor in CSS Fonts Module Level 5 "defines a multiplier for glyph outlines and metrics associated with this font, to allow the author to harmonize the designs of various fonts when rendered at the same font-size". css-fonts-5 is a Working Draft (as at Feb 2022), but many browsers have support 'size-adjust' since late 2021.

In the example below, size-adjust is used to make 'courier-new 12pt' and 'Consolas 12pt' render with near-identical width; normally 'Courier New 11pt' is required to match the width of 'Consolas 12pt'.

@font-face {
  font-family: courier-new;
  src: local(Courier New);
  size-adjust: 91.6%
}
<p style="font-family: 'Courier New'; font-size: 11pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>
<p style="font-family: courier-new; font-size: 12pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>
<p style="font-family: Consolas; font-size: 12pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>

2022-02-07

Solution

 6

I understand what you want, but I think the answer to your question is "No, this can't be done in CSS", at least not in CSS2 afaik.

Hoping someone can prove me wrong, 'cause i want this too :D

I suppose JS can accomplish this, at least up to some point. Not sure if there is a "is this font installed?" method in JS, but you may be able to make some educated guesses based on OS and such. Got no experience there sorry.

Edit: some quick googling does provide a few clever JS tricks, though I haven't tried them yet. E.g. http://remysharp.com/2008/07/08/how-to-detect-if-a-font-is-installed-only-using-javascript/

Another edit, after some more searching: I was triggered by the "someone should propose it" :D. It seems CSS3 spec has the "font-size-adjust", which may be of use here. However, support in browsers other than Firefox may not be optimal at the time I write this. Here's the W3 word on that property: http://www.w3.org/TR/WD-font/#font-size-adjust

2011-05-11