Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style SVG <g> element?

I have some SVG elements grouped together in a <g> element. I just want to style that <g> element to show grouping of elements. Like I want to give some background-color and a border to it. How it would be achieved?

I tried fill and stroke attribute to <g> element, but it doesn't work. How it would be possible? Thanks in advance!

Sample Here

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">     <g fill="blue" stroke="2">             <rect id="svg_6" height="112" width="84" y="105" x="136" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="5" stroke="#000000" fill="#00ff00"/>         <ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="271" cy="156" id="svg_7" rx="64" ry="56"/>     </g> </svg> 
like image 447
Sudarshan Avatar asked Sep 09 '13 11:09

Sudarshan


People also ask

How do you style a G tag?

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. EDIT: updated wording and added fiddle in comments. The <rect> is not allowed to have shapes or <g> as chidlren (not even in SVG2).

What is the G in SVG?

The SVG <g> element is a container used to group other SVG elements. Transformations applied to the <g> element are also performed on its child elements, and its attributes are inherited by its children.

Can you style an SVG?

It is possible to style your SVG shapes using CSS. By styling is meant to change the looks of the shapes. This can be stroke color and width, fill color, opacity and many other properties of your shapes.

Can CSS apply to SVG?

There are many Scalable Vector Graphics (SVG), but only certain attributes can be applied as CSS to SVG. Presentation attributes are used to style SVG elements and can be used as CSS properties. Some of these attributes are SVG-only while others are already shared in CSS, such as font-size or opacity .


1 Answers

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.

like image 126
Boldewyn Avatar answered Oct 01 '22 04:10

Boldewyn