Search code examples
csssvginkscape

Add css to svg with inkscape


I use Inkscape for creating svg images and want to know how to use not embedded css rules.

For example

  • draw rectangle
  • in XML-editor add class attribute as

    class="rect1"

to svg:rect object

How to add css like

.rect1 { fill:#ffef00; }


Solution

  • Here's an example of an SVG in an HTML page that you can style with CSS:

    HTML page

    <div id="mySvg">
      <svg>
        <use xlink:href="images/logo.svg#shape" />
      </svg>
    </div>
    

    The SVG (located at images/logo.svg)

    <svg version="1.1" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <g id="shape">
            <rect x="50" y="50" width="50" height="50" />
            <circle cx="50" cy="50" r="50" />
        </g>
      </defs>
    </svg>
    

    The CSS

    svg {
        fill: currentColor;
    }
    
    #mySvg {
        color: green;
    }
    

    See working example: plunker

    Notes

    • If you use Inkscape to create your SVG, you'll probably have to do some hand-editing of the SVG to make it styleable with CSS.
    • Make sure the SVG code doesn't have any fill attributes in it (fill should be in the CSS). When making an SVG with Inkscape, it often has a fill:none or something. You'll have to manually remove those.
    • When using Inkscape, save files as "Optimized SVG" as described here.