14

I'm trying to use CSS variables to generate a dynamic path.

Example:

:root {
  --fonts-path: "/path/to/font";
}

@font-face {
  font-family: "FontName";
  src: url(var(--fonts-path) + "/FontName-Light.woff") format('woff');
  font-weight: 100;
}

html {
  font-family: 'Metric', Arial, sans-serif;
}

This is failing with a not-found module 'var(--hpe-fonts-path', this is the webpack log:

ERROR in ./~/css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./~/postcss-loader!./src/theme/fonts.css
Module not found: Error: Cannot resolve module 'var(--fonts-path' in /Users/project-sample/src/theme
 @ ./~/css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./~/postcss-loader!./src/theme/fonts.css 6:83-114 6:234-265 6:403-434 6:576-607

Any pointers?

Alan Souza
  • 7,095
  • 9
  • 42
  • 65

4 Answers4

6

I see some problems with your approach:

  • @font-face rules don't inherit CSS variables set on :root.

  • You can't use + to concatenate CSS strings. See string concatenation in css

  • Not all implementations support var() inside url() yet.

Community
  • 1
  • 1
Oriol
  • 249,902
  • 55
  • 405
  • 483
2

A similar issue is described in this post:

CSS native variables not working in media queries

where the user tries to use a variable inside a @font-face rule.

As described in the accepted answer (https://stackoverflow.com/a/40723269/4879632) you cannot use variables inside of rules, because the variables are inherited by :root (html) child elements. @ Rules (font faces, media queries, etc) are not elements, so they do not inherit from the root. Thus, you cannot reference a variable from there.

Kantharis
  • 826
  • 1
  • 7
  • 19
1

Try incluiding the url inside the variable, This works in a background context, but not sure if it does inside font-face

:root { 
--url:url("https://picsum.photos/id/1/200/300"); 
}

.box { 
background:var(--url); 
}
gtamborero
  • 2,379
  • 22
  • 22
1

You can't concatenate variable in CSS (refer here):

Since you can't concatenate in CSS (aside from the content property), CSS variables can not be concatenated. This means, for example, you can't combine a CSS variable that is a number with a unit.

// No version of this will work 
div {
  --height: 100;
  height: var(--height) + 'px';
}
Adrian Mole
  • 43,040
  • 110
  • 45
  • 72