CSS Variables and String concatenation

Alan Souza picture Alan Souza · Jul 12, 2016 · Viewed 15.8k times · Source

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?

Answer

Oriol picture Oriol · Jul 12, 2016

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.