Moving to SVG icons - how to separate them from th

2019-06-21 20:49发布

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?

7条回答
老娘就宠你
2楼-- · 2019-06-21 21:24

In order to preserve the niceties of SVG icons, there is at the moment no alternative to including the <svg> in your HTML page.

Chris Coyier's article describes the generally accepted best practice for inclusion. It's something like:

  1. Store your SVG icon definitions as <symbols>:

    <svg id='my-icons'>
       <symbol id='icon-puppy'> <!-- puppy icon goes here --> </symbol>
       <symbol id='icon-kitty'> <!-- kitty icon goes here --> </symbol>
    </svg>
    
  2. When you need to use an icon, reference the icon definition:

    <svg class='icon'>
       <use xlink:href='#icon-puppy'/>
    </svg>
    

This article describes how you might go about including the SVG file in the HTML dynamically.

查看更多
登录 后发表回答