28

I have an inline SVG image I use as a background, a simlified example is below:

div {
  width: 100%; height: 500px;
  color: green;
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><path d='M0 0 H 100 V 100 H 0 Z' fill='currentColor'></path></svg>");
}

https://jsfiddle.net/wjqkL07p/3/

The problem is that the image doesn't inherit the currentColor and is black when I expected it to be green. Any idea?

sdvnksv
  • 9,350
  • 18
  • 56
  • 108
  • 7
    because when using url() you are fetching external ressource even if it's not exactly the case, so there is no way to use current color of CSS within your SVG – Temani Afif Mar 20 '18 at 10:22
  • 9
    You can't easily do this. There's some hacky ways to do it here: https://codepen.io/noahblon/post/coloring-svgs-in-css-background-images – Peter Collingridge Mar 20 '18 at 10:27
  • @TemaniAfif I reopened this question because the *question* is distinct from those that you marked it as a duplicate of, even if one of the work arounds mentioned in those questions (use a different method of coloring the SVG) is required. I recommend that you turn your comment above into a more full answer on this question! – Zach Saucier Apr 13 '23 at 13:48
  • @ZachSaucier my comment is already an answer in the duplicate ... that's whay I closed as dupicate – Temani Afif Apr 13 '23 at 14:20

1 Answers1

5

This doesn't work as you expect it to because using url() makes the SVG be treated as if it were an external resource, even if it's not exactly the case. So there is no way to use CSS' currentColor within your SVG when it's a background image.

For this specific case, you could instead use a mask and use the background-color to update the color. Make sure you fill your SVG with a non-transparent color.

div {
  height: 300px;
  background-color: green;
  -webkit-mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><path d='M0 0 H 80 V 100 H 0 Z' fill='black'></path></svg>");
}
<div></div>
Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Temani Afif
  • 245,468
  • 26
  • 309
  • 415