Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG reuse a group but change fill color

Tags:

svg

So I have a <g> element with some <rect>s inside it, they all have same fill color, but can be of different sizes. I want to reuse the <g>, but fill it with a different color, is it possible?

I can change the markup any way I like.

like image 902
Spadar Shut Avatar asked Jul 28 '11 08:07

Spadar Shut


People also ask

How to group elements in SVG?

Grouping elements with the elementThe <symbol> element is similar to the group element <g> —it provides a way to group elements together.

How to reuse SVG?

The SVG <use> element can reuse an SVG shape from elsewhere in the SVG document, including <g> elements and <symbol> elements. The reused shape can be defined inside the <defs> element (which makes the shape invisible until used) or outside.


1 Answers

You can define the rect group using <defs> like so:

<defs>
    <g id="rect-group">
        <rect x="0" y="0" width="60" height="30"/>
        <rect x="20" y="10" width="20" height="50"/>
    </g>
</defs>

Then you can use this group multiple times, putting it in different places with with transform if you like:

<g class="group-1" transform="translate(10.5,20.5)">
    <use xlink:href="#rect-group" />
</g>

<g class="group-2" transform="translate(55.5,32.5)">
    <use xlink:href="#rect-group" />
</g>

You can style these groups directly or give them different classes as above and use CSS to style as you like:

  <style> 
    .group-1{
        fill: red;
        stroke: white;
    }
    .group-2{
        fill: blue;
        stroke: black;
    }
  </style>

For an example, see: http://dl.dropbox.com/u/169269/rect_group.svg

like image 176
Peter Collingridge Avatar answered Jan 24 '23 03:01

Peter Collingridge