ivarni
ivarni

Reputation: 17878

Dynamically styling a (non-inline) SVG with CSS or Javascript

At the project I'm on we're using SVGs for icons. Most of our icons need to have a second version where the color is inverted (as in a blue icon for white background and a white icon for blue background).

We're including the icons using background-image in CSS.

I am trying to figure out if there is a way we can have only one file for each icon, and use CSS or Javascript to change it's color. That would let us get away with fewer requests.

Now, I know that using CSS to set properties on an inline SVG image works, but I don't really want to inline every icon we've got.

Is there a way to do this?

I have a Plunker where an SVG is included in three different ways. Inline, CSS background and the img tag. There's a CSS rule that sets the fill attribute and that only hits the inlined SVG. There's also a little Javascript snippet that tries to find all the circles and color them. Interestingly enough, setting fill directly on the inlined SVG does not work when fill is already set via CSS.

It seems that document.querySelectorAll will only find the inlined SVG, which I guess makes sense. The other two are strictly speaking not part of the DOM.

Now, is there any way I can override the fill of the last two circles without making changes in the circle.svg file? Is there some other trick I can use to display the circle.svg file with two different colors?

Upvotes: 5

Views: 2244

Answers (1)

Mathias
Mathias

Reputation: 5670

If you want to take a different approach to solving your problem, you can use an icon font generated from your SVG images and set the text color to white, blue or any other color. The browser must support custom fonts (@font-face) but I think most browsers that support SVG images will support this

There are a few different services that will let you create your own font like: http://icomoon.io/ or http://fontastic.me/

As an example: Bootstrap uses a subset of an icon font for their icons: http://getbootstrap.com/components/#glyphicons

Upvotes: 2

Related Questions