csswebfontscss-variables

Combine css variables into one variable


I'm trying to combine/compose multiple css variables into one that I can use but it doesn't seem to be working. In particular I'm trying to combine separate font rules into one where I can then use the font shorthand.

Here is the pertinent part of my variable declarations on root:

:root {
    --Font-Family-Regular: 'my-custom-web-font', verdana, sans-serif;
    --Font-Family-Regular-Weight: 400;
    --Font-Family-Regular-Style: normal;

    --Body-Font:
        var(--Font-Family-Regular-Style)
        var(--Font-Family-Regular-Weight)
        var(--Font-Family-Regular);
    }
}

Then in my css I reference the css variable where I combining other variables:

body {
  font: var(--Body-Font);
}

But I don't get my web font as I would expect. Is combining/composing like this not possible?

The web fonts are loading fine. If I reference a font family variable on a font-family property, it all works fine. I have regular/bold/semi-bold/italic versions all working with single css variables for each, I'm just trying to combine the family, weight and style into one variable.


Solution

  • There are some fairly strict rules about the order in which you have to place the values for font:

    AND you must include a the font-size. AND some values must come before the font-size.

    See https://developer.mozilla.org/en-US/docs/Web/CSS/font for details.

    Here is an example using your CSS, (with bold weight chosen so we can see it's been applied).

    <style>
      :root {
        --Font-Family-Regular: 'my-custom-web-font', verdana, sans-serif;
        --Font-Family-Regular-Weight: bold;
        --Font-Family-Regular-Style: normal;
    
        --Body-Font: var(--Font-Family-Regular-Style) var(--Font-Family-Regular-Weight) 72px var(--Font-Family-Regular);
      }
    
    
      body {
        font: var(--Body-Font);
      }
    </style>
    
    <body>some text</body>