10

CSS variables don't work when used in an SVG background-image:

.icon-24 {
  width: 24px;
  height: 24px;
  display: inline-block;
  vertical-align: middle;
  background-repeat: no-repeat;
  background-color: silver;
}

.icon-24-stroke {
  --color-test: red;
  background-image: url("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='none' stroke='var(--color-test)' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='10' stroke-width='1px'> <circle cx='12' cy='12' r='8' /> </svg>");
}

.icon-24-fill {
  --color-test: red;
  background-image: url("data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='var(--color-test)'><circle cx='12' cy='12' r='8' /></svg>");
}
<p>The circle stroke should be red:</p>
<i class="icon-24 icon-24-stroke"></i>
<p>The circle fill should be red:</p>
<i class="icon-24 icon-24-fill"></i>

Is there a way to make this work?

TylerH
  • 20,799
  • 66
  • 75
  • 101
François Romain
  • 13,617
  • 17
  • 89
  • 123
  • 2
    [Not with url()](https://stackoverflow.com/questions/42330075/is-there-a-way-to-interpolate-css-variables-with-url/42331003#42331003), unless you use JavaScript instead of var(). – BoltClock Feb 21 '18 at 15:56
  • 2
    background images are a separate document to the host page. CSS is per document so not only do CSS variables not work, no CSS from the host page works. – Robert Longson Feb 21 '18 at 15:59
  • 6
    @Robert Longson: These images are supplied via data URIs which are designed specifically to render that a non-issue. The only thing that's stopping this from working is url() itself being incompatible with var() for historical reasons. Were that not an issue, parameterizing the data URIs with var() would work flawlessly. – BoltClock Feb 21 '18 at 16:02
  • Even though it is "physically" in the same document, the SVG inside the Data URL is treated exactly the same as if it was a separate document. – Paul LeBeau Feb 22 '18 at 12:33
  • Not possible, but there are some [helpful alternatives here](https://stackoverflow.com/questions/51395179/svg-fill-with-css-variables) – Carol Skelly May 19 '21 at 13:01
  • For anyone using framework like `Blazor`, you can use parameters within svg using the `@` symbol. `stroke='@SomeColor' stroke-width='2'` – clamchoda Feb 16 '23 at 16:12

1 Answers1

3

Like @BoltClock said in the comments, it's not possible to use css variables in urls.

François Romain
  • 13,617
  • 17
  • 89
  • 123