Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use css variables in a svg background-image?

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?

like image 797
François Romain Avatar asked Feb 21 '18 15:02

François Romain


People also ask

Can you use CSS variables in SVG?

CSS custom properties can be used to style SVGs inline.

Can SVG be background image CSS?

SVG images can be used as background-image in CSS as well, just like PNG, JPG, or GIF. All the same awesomeness of SVG comes along for the ride, like flexibility while retaining sharpness. Plus you can do anything a raster graphic can do, like repeat.

Can we use SVG code in background image?

SVG must have attribute xmlns like this: xmlns='http: //www.w3.org/2000/svg' . If it doesn't exist, it will be added automagically. Encoded SVG can be used in background , in border-image or in mask (live demo).


1 Answers

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

like image 65
François Romain Avatar answered Oct 25 '22 11:10

François Romain