For each of the following h1
and h2
elements, the below CSS specifies a font-family
in two alternative ways: (a) as the traditional string, e.g., font-family: Tangerine,cursive;
and (b) as a previously defined CSS variable, e.g., font-family: var(--my-font-family-cursive);
, one of which alternatives is commented out.
You can also see my code in this CodePen Pen.
When I use the traditional string specification (commenting out the CSS-variable specification), everything works fine. Each heading is rendered in its desired font, as in this screenshot:
However, when I comment the string specification and uncomment the CSS-variable specification, the font-family
specification is ignored entirely and the rendering defaults to my browser's user-agent spec serif
, as in this screenshot:
Both Chrome and Firefox developer tools consider, for example, font-family: var(--my-font-family-cursive);
to be "Invalid property value". See screenshot.
Note that I use corresponding CSS-variable syntax to define font colors --my-font-color
and --my-font-color-cursive
and these font colors are recognized, leading to a red h1
and a blue h2
.
It must be the case that I'm overlooking something stupid, but I can't figure out why my CSS-variable formulation is being rejected.
Here's just one example from the "CSS literature" that seems to endorse precisely what I'm doing: CSS Variables — How To Use CSS Custom Properties . This source gives the following example:
:root {
--headings-font-family: "Times New Roman", Times, serif;
}
h2 {
font-family: var(--headings-font-family);
}
Here's the code I describe above (which is also at this CodePen Pen):
<html>
<head>
<title>MWE: CSS variable for font-family not working</title>
<style>
@import url(https://fonts.googleapis.com/css?family="PT Sans");
@import url(https://fonts.googleapis.com/css?family=Tangerine);
:root {
--my-font-family: "PT Sans", sans-serif ;
--my-font-family-cursive: Tangerine, cursive ;
--my-font-color: red ;
--my-font-color-cursive: blue ;
}
h1, h2 { font-size: 3em ; }
h1 {
color: var( --my-font-color ) ;
/* font-family: "PT Sans", san-serif ; */
font-family: var ( --my-font-family ) ;
}
h2 {
color: var( --my-font-color-cursive ) ;
/* font-family: Tangerine, cursive ; */
font-family: var ( --my-font-family-cursive ) ;
}
</style
</head>
<body>
<h1>Just some text</h1>
<h2>Some more text</h2>
</body>
</html>