2

I have a circle.svg file

<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  width="48" height="48">
  <circle class="circle" cx="24" cy="24" r="24"></circle>
</svg>

And a HTML file

...
<div class="bullet blue">
  ...
</div>
<div class="bullet red">
  ...
</div>
<style>
.bullet:before {
  content: url(circle.svg);
}
.bullet.blue:before {
  .circle {
    fill: #0000FF;
  }
}
.bullet.red:before {
  .circle {
    fill: #FF0000;
  }
}
</style>

I want the circle be filled by the style sheet, but it's not working. However if I embed the svg code into the HTML, the style sheet would take effect on it, but I don't want to insert extra resources in HTML code. Is there a way to do it via CSS? If not, how about using JavaScript?

Rix
  • 1,688
  • 13
  • 20
  • Possible duplicate of [Can I change the fill color of an svg path with CSS?](http://stackoverflow.com/questions/9529300/can-i-change-the-fill-color-of-an-svg-path-with-css) – Simon Staton Aug 29 '13 at 10:01

2 Answers2

3

Styles don't apply across documents and the SVG and HTML you have there are separate documents.

If you embedded the circles via two <object> or <iframe> tags it would be possible to do what you want as you could access and manipulate the SVG DOM then i.e.

var svgDoc = document.getElementById("objectId1").contentDocument;
var style = svgDoc.createElementNS("http://www.w3.org/2000/svg". "style");
style.textContent = ".circle { fill: #0000FF; }";
svgDoc.rootElement.appendChild(style);

And similarly for the other <object> tag.

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

I don't think that if you set the svg as an external resource, you would be able to modify its inner properties with css or javascript It would be like trying to style an iFrame with css.

several solutions :

  1. Embed your SVGs in your html
  2. create a sprite from the SVG with a blue and red circle and only move the background-position
  3. create multiple SVG and call them separately depending on the class. Hope that helps.
Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139
Abdoul Sy
  • 580
  • 3
  • 10