2

I'd like to use an SVG image as a CSS sprite through a content property, bootstrap-style, like so:

i.rectangle-image {
  content: url(rectangle.svg);
}

and here's my SVG:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80"/>
</svg>

and proposed HTML:

<div><i class="rectangle-image"></i> Hello, world!</div>

I'd like to be able to re-colour the SVG in my application, for example to have the icon appear purple in some locations, and white in others. I know I can accomplish this by having three different SVG files (or data URIs) with the fill attribute set differently on the <rect> tag, but I'm wondering if there's a way for me to do this through CSS in my HTML?

I've tried adding a fill attribute to the i.rectangle-image selector, but that doesn't work.

I've looked at this answer and it's not quite what I want. They suggest embedding SVG throughout the page, and I'd prefer to do this via CSS content if possible. Any thoughts? Am I out of luck?

Community
  • 1
  • 1
Jonathan
  • 7,536
  • 4
  • 30
  • 44

3 Answers3

4

If you use the CSS content facility you're loading the SVG data basically as an image. For privacy reasons you can't affect how the image is displayed using external CSS or javascript.

If you want to change the contents of SVG data you'd either have to load it via an <object> or <iframe> tag or put it inline in the HTML file.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
0

What abouth giving the SVG transparency and fill the background using css background color?

The sugested solution from @MMM looks great:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="13px" height="12.917px" viewBox="0 0 13 12.917" enable-background="new 0 0 13 12.917" xml:space="preserve">
       <polygon fill="#000000" points="6.504,0 8.509,4.068 13,4.722 9.755,7.887 10.512,12.357 6.504,10.246 2.484,12.357 3.251,7.887 0,4.722 4.492,4.068 "/>
       <script>
         document.getElementsByTagName("polygon")[0].setAttribute("fill", location.hash);
       </script>
</svg>

http://jsbin.com/usaruz/2/edit

http://codepen.io/Elbone/pen/fHCjs

Karl Adler
  • 15,780
  • 10
  • 70
  • 88
0

You can use SVG Image Editor tool to edit the colors in front end and copy the code and use it where you wanna place it, which requires short time of period.. Try it surely it will work out