How to style SVG <g> element?
Solution 1:
You cannot add style to an SVG <g>
element. Its only purpose is to group children. That means, too, that style attributes you give to it are given down to its children, so a fill="green"
on the <g>
means an automatic fill="green"
on its child <rect>
(as long as it has no own fill
specification).
Your only option is to add a new <rect>
to the SVG and place it accordingly to match the <g>
children's dimensions.
Solution 2:
You actually cannot draw Container Elements
But you can use a "foreignObject" with a "SVG" inside it to simulate what you need.
http://jsfiddle.net/VBmbP/4/
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
<foreignObject id="G" width="300" height="200">
<svg>
<rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>
</svg>
<style>
#G {
background: #cff; border: 1px dashed black;
}
#G:hover {
background: #acc; border: 1px solid black;
}
</style>
</foreignObject>
</svg>
Solution 3:
I know its long after this question was asked and answered - and I am sure that the accepted solution is right, but the purist in me would rather not add an extra element to the SVG when I can achieve the same or similar with straight CSS.
Whilst it is true that you cannot style the g
container element in most ways - you can definitely add an outline to it and style that - even changing it on hover of the g
- as shown in the snippet.
It not as good in one regard as the other way - you can put the outline box around the grouped elements - but not a background behind it. Sot its not perfect and won't solve the issue for everyone - but I would rather have the outline done with css than have to add extra elements to the code just to provide styling hooks.
And this method definitely allows you to show grouping of related objects in your SVG's.
Just a thought.
g {
outline: solid 3px blue;
outline-offset: 5px;
}
g:hover {
outline-color: red
}
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
<g>
<rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>
</g>
</svg>
Solution 4:
The style that you give the "g" element will apply the child elements, not the "g" element itself.
Add a rectangle element and position around the group you wish to style.
See: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
EDIT: updated wording and added fiddle in comments.