Search code examples
javascriptjqueryhtmlcsssvg

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?

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>

Solution

  • You actually cannot draw Container Elements

    But you can use a "foreignObject" with a "SVG" inside it to simulate what you need.

    https://jsfiddle.net/csoyefb9/

       <svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
           <foreignObject id="G" width="300" height="200">
                <svg id="S">
                  <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>
                      #S {
                        background: #fcf; border: 1px dashed black;
                      }
                      #S:hover {
                        background: #cac; border: 1px solid black;
                      }
                </style>
         </foreignObject>
    </svg>