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?

1

2 Answers 2

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.

1
  • Yes, I finally made it with JavaScript and a template system.
    – Rix
    Commented Aug 29, 2013 at 11:56
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.