0

Just like how CSS styles like fill, stroke being set via CSS, is there a way to set image (background-image) to an SVG element using CSS alone? Some existing solutions have <image> tag within the <svg> element, but I don't want to have that since I'm using a third-party library that generates the SVG, so CSS seems to be a good alternative.

Update: I would like to add a background to a specific svg element, not the whole SVG. Didn't realize that it wasn't mentioned in the actual question earlier.

2 Answers2

1

I think the only way you can do what you want is to define your pattern fills in a separate SVG. Then you can assign those predefined patterns via CSS.

Demo:

.filled {
  fill: url(#image-fill);
}
<svg width="0" height="0">

  <!-- image fills defined here in this hidden SVG -->
  <defs>
    <pattern id="image-fill"
             patternContentUnits="objectBoundingBox" width="1" height="1">
      <image x="0" y="0" width="1" height="1" preserveAspectRatio="xMidYMid slice"
             xlink:href="https://placekitten.com/400/400"/>
    </pattern>
  </defs>

</svg>



<svg viewBox="0 0 500 500">
  <path class="filled" d="M 100,50 L 450,200 L 150,350 Z" stroke="grey"/>
</svg>
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
0

Just add it via CSS. Run the snippet to see it work:

svg{
  background: url("https://www.fillmurray.com/79/79");
}
<svg width="400" height="160" viewBox="0 0 400 160">
  <circle cx="200" cy="80" r="30" fill="red" stroke="white" stroke-width="4"></circle>
</svg>
Ted
  • 14,757
  • 2
  • 41
  • 58