0

I want to use my CSS variable into an background image for changing the fill property of the SVG.

:root{
  --primary: red;
}

input {
  background-image: url('data:image/svg+xml,<svg    fill="var(--primary)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z"/></svg>');
  background-position: right center;
  background-repeat: no-repeat;
}
<input type="text>
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
Raphael
  • 1
  • 3
  • 2
    Similar thread that may help, It is impossible to modify the svg in background image, however this thread talks about serving the svg up from a custom endpoint https://stackoverflow.com/questions/13367868/modify-svg-fill-color-when-being-served-as-background-image – Cameron May 27 '21 at 14:23
  • related: https://stackoverflow.com/q/67025375/8620333 – Temani Afif May 27 '21 at 14:25

2 Answers2

1

Not as elegant maybe, but you could do something like this.

:root{
  --red: url('data:image/svg+xml,<svg fill="red" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z"/></svg>');
  --blue: url('data:image/svg+xml,<svg fill="blue" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><path d="M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z"/></svg>');
  --primary: var(--red);
}

input {
  background-image: var(--primary);
  background-position: right center;
  background-repeat: no-repeat;
}
<input type="text">
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
0

Unfortunately, you can't change svg fill/stroke property, if is used as background-image. You could do it only if svg is inside the HTML as a code.

fromaline
  • 507
  • 3
  • 8