Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving to SVG icons - how to separate them from the code?

Tags:

html

css

icons

svg

SVG icons have some advantages over font icons: they can be scaled to fit a variable-sized container element, and you can theoretically change color of individual paths. I also like the fact that I can easily make them in Inkscape :P

But how do I move the SVG in the CSS file so they can be reused on the same page, like icon fonts, and still benefit from these advantages?

The background property supports SVG, with background: url(#svg_element), but that means I have to put the SVG in the HTML :| If I put it as a "data" string, how do I change path colors in the same css file?

like image 581
Alex Avatar asked Jan 14 '15 23:01

Alex


1 Answers

But how do I move the SVG in the CSS file so they can be reused on the same page, like icon fonts, and still benefit from these advantages?

With svg templates

Lets create a svg template.

Template (html)

<svg width="100px" height="100px" viewBox="0 0 100 100" class="hide">
    <circle id="circle-tmp" cx="50" cy="50" r="50" />
</svg>

Its a template so we hide it. (but still in the DOM)

.hide { display: none;} //css

Use (html)

<svg viewBox="0 0 100 100" class="circle-first">
    <use xlink:href="#circle-tmp" />
</svg>

This can be reused anywhere on the page.

how do I change path colors in the same css file?

Easy, just style it!

css

.circle-first {
    fill: #12bb34;
}

Working example? Here you go: Fiddle

Browser support? Not 100% sure, but svg support in all big browsers: CanIUseIt

like image 113
Persijn Avatar answered Nov 15 '22 07:11

Persijn