A woman's arms enfolding a group of bright leaves and flowers

Cet article est également disponible en français

Groups - the <g> tag in - are somewhat akin to <div> elements on web pages, in that they contain and control related SVG elements. However, there are some very distinct differences between <g> and <div> elements are important to understand:

  1. Just like <div> elements, <g> elements allow their children to inherit presentational styles:
    <svg viewBox="0 0 400 160">
        <g fill="#33E" stroke="#000" stroke-width="10px">
            <circle  cx="88" cy="80" r="62"/>
            <rect x="246" y="17" width="123" height="123"/>

    Which produces:

  2. Similarly, transforms on groups are inherited by the elements inside them.
  3. However, unlike <div> elements, SVG groups cannot be positioned. They can be translated into new locations via a transform, but because they do not have x or y attributes, they cannot be positioned in the SVG document*.
  4. Again like <div> elements, <g> elements can take an id attribute (and less commonly, classes), for further styling or scripting:
    <svg viewBox="0 0 400 163">
    <style type="text/css">
        #svg-container { 
            fill: hsl(45,80%,80%);
            stroke: rgba(0,0,0,0.3);
            stroke-width: 10px;
        <g id="svg-container">
            <circle  cx="88" cy="80" r="62"/>
            <rect x="246" y="17" width="123" height="123"/>

    Which creates:

    (And just like CSS inheritance, presentational rules applied directly to elements will overwrite any rules from their parent if the two conflict)

  5. Finally, unlike <div> elements, <g> elements can have the own nested <title> and <desc> elements for further information and accessibility.

* You can get around this by nesting <svg> elements inside groups, since SVG elements do have x and y attributes. I’ll explore this advanced topic later.

Photograph by Dina Belenko, used with permission

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.