18

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,475
  • 10
  • 46
  • 68

6 Answers6

9

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
  • 274,082
  • 63
  • 437
  • 513
3

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,898
  • 27
  • 28
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
  • 1,316
  • 1
  • 11
  • 21
2

You can combine a variable with a unit like this:

:root {
  --twenty: 20;
}
.box {
  width: calc( var(--twenty) * 1px );
  height: calc( var(--twenty) * 1px );
}
<div class="box" style="background:red;"></div>
Jules Colle
  • 11,227
  • 8
  • 60
  • 67
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
  • 49,934
  • 160
  • 51
  • 83
0

You Should Do it like this to concat some variable using after value in css variable

:root{
  --scroll:0;
  --scrollunit:1deg;
}

.someclass{

    rotate:calc(var(--scroll) * var(--scrollunit));

}

https://codepen.io/abhishek-bhardwaj/pen/VwVyrmb