Can I use CSS variables in a font list and have it work in legacy browsers?

Viewed 16432

I'd like to use a CSS variable to store a font in case the user doesn't have the specified font installed.

Example:

:root {
     --common-font: Comic Sans MS;
}

.header1 {
     font-family: CoolFont1, var(--common-font);
}

Will legacy browsers break if I add a reference to the variable in the font names?

https://caniuse.com/#feat=css-variables

2 Answers

Yes, it will break, you must use fallback font for legacy browser without using CSS variables.

For example:

   .header {
       font-family: sans-serif; /* This is fallback font for old browsers */
       font-family: var(--common-font);
    }

Also you can use a @supports condition with a dummy feature query:

.header {
    @supports ( (--a: 0)) {
      /* supported */
      font-family: var(--common-font);
    }

    @supports ( not (--a: 0)) {
      /* not supported */
      font-family: sans-serif; /* This is fallback font for old browsers */
    }
}

Definitely, it will break in legacy browser. However I think one can use postcss-css-variables plugin to do the conversion. So that you can keep on using the CSS variable feature, but do not need to worry too much on legacy browser. When those legacy browsers fades out, you can just remove the plugin.

Checkout https://www.npmjs.com/package/postcss-css-variables for details.

It also has a playground, which you can play around to see how it behaves.

For example,

    :root {
        --color-background: #ffaaaa;
        --font-color: #2222ff;
    }

    @media (prefers-color-scheme: dark) {
        :root {
            --color-background: #aaaaff;
            --font-color: #ffFF22;
        }
    }

    body {
        background-color: var(--color-background);
    }
    
    p {
        color: var(--font-color);
    }

will be convert to

    body {
        background-color: #ffaaaa;
    }

    @media (prefers-color-scheme: dark) {

        body {
            background-color: #aaaaff;
        }
    }
    
    p {
        color: #2222ff;
    }
    
    @media (prefers-color-scheme: dark) {

        p {
            color: #ffFF22;
        }
    }
Related