Structuring, Grouping, and Binding in SVG Elements , , and

Original author: Sara Soueidan
  • Transfer
SVG provides opportunities for structuring a document using special elements that allow you to define and group objects, as well as refer to them in the future. They simplify code reuse while keeping it clean and readable. This article will examine these elements, as well as their differences and benefits.

Grouping using an item

Element used to logically group a set of related graphic elements. This can be compared with the grouping of objects in graphic editors.

Elementcombines all its contents into a group. As a rule, he is given an identifier by which the appeal will be made in the future. Any styles applied to an element.will also be applied to all its descendants. This allows you to set styles and transformations, as well as add interactivity and animation immediately to a whole group of objects.

As an example, we will use a bird drawn in SVG. It consists of several separate figures described by circles and paths. [For obscure reasons, the author described circles in ways instead of using circles, although it was promised to use circles. Do not ask why. I fixed it. Do not ask why. - Per .]

Bird drawing code

example Let's say you draw such a bird in Illustrator. If you need to move it from one place to another, the grouping of objects simplifies this task, since it allows you to not move each element individually. Grouping in SVG does roughly the same thing. In the example above, in addition to the general group for the entire bird (id = "bird"), we also identified subgroups that define the head and body separately (id = "body", id = "head").

If you change the fill color of the #body group, the fill of all elements within the group will change. It can be very convenient. [We are talking about elements for which the fill color is not set explicitly. For example, in the same #body, the #wing element has its own color. - Per .]

Grouping elements can be very useful not only for organizing and structuring a document. It can be of particular benefit if you want to add interactivity to the SVG graphics or set some transformations. Having grouped the elements, you can move them, scale or rotate all together, maintaining their position relative to each other.

So, in the case of a grouped bird, you can scale it with just one line of CSS:
#bird {transform: scale(2);}

Grouping adds convenience when implementing interactivity. You can hang the mouse events on the whole bird and make it react as a whole. This is much more convenient than doing the same for each element individually.

Element has another important and interesting feature: it can contain tags и <desc>, которые позволят изображению быть обработанным Screen Reader'ами [Программы воспроизведения текста для людей с ограниченными возможностями; не нашел емкого и адекватного перевода термина. — <em>Пер</em>.]; также они позволяют сделать код более читаемым для человека. Пример использования:<br> <pre><code class="html"><g id="bird"> <title>BirdAn image of a cute little green bird with an orange beak.

Reusing items with

When working with graphics, you can often find a situation where repeating elements are used. In graphic editors in this case, the copy-paste method is usually used, which is more convenient than creating an element from scratch.

In SVG, an element implements similar functionality.. It can be used to reuse both individual elements and groups of elements.

Elementaccepts x and y coordinates, height, width and a link to the source element (xlink: href) as attributes. The reference is the identifier of the object.

For example, if we want to add another bird, instead of copying its code, you can use the tag:
Codepen example

Note that in the xlink: href attribute you can refer to any SVG element, even located in an external file. This is very convenient to use for organizing (for example, you can have a file with reusable components) or for caching frequently used files.

Let's say our bird was created in a separate animals.svg file. In this case, you can refer to it like this:

Keep in mind that links to external SVGs in do not work in most versions of IE (prior to IE 11). I recommend that you read the article by Chris Coyier , which describes how to circumvent this restriction.

The most attentive readers must have noticed that the coordinates given to the elementnot from the origin of the entire SVG image. This is actually a shortened form for the transform attribute. The following two lines are equivalent:


Simply put, the coordinates of an element are relative to the source element. This behavior is not always optimal and may be a disadvantage.

Another disadvantageis that the copies will use the same styles as the original element. When applying styles or transformations to the #bird group, these styles and transformations will apply to all its copies.

However, you can still apply an independent transformation to the element. For example, the following line of code allows you to reuse a bird whose dimensions will be only half the size of the original:

[In this case, the principle of the coordinate system may seem somewhat unexpected. It also scales. If the original element was positioned 100 pixels from the edge of the image, then such a copy will be located 50 pixels from the edge. Given x and y, this also applies. Thus, the words about the location of the copy relative to the original element are not entirely correct. - Trans .]

Unlike conversions, copy styles cannot be redefined. Thus, if you want to create an army of birds of different colors, then use will fail (unless the source element is defined inside without their own styles, but more on that in the next section).

Elementallows you to reuse an element that is already displayed on the SVG image. If you just want to identify the element without displaying it, and then draw it in the right place when needed, the element will come to the rescue.

Reusing Stored Items with

Element can be used to store content that will not be displayed during the definition. The content in it is stored in a hidden form and waits in the wings when it is used and displayed by other SVG elements, which makes it ideal, for example, for use in patterns.

Stored incan do anything, starting with a group of elements, like our bird, and ending with a mask or gradient. This is a template for future reference. By itself, it is never displayed, only entities using it.

The following is an example in which the gradient is first determined and then used to fill the rectangle:
Gradient filled rectangle code
Example on codepen

[The author made an annoying mistake: the height and width of the rectangle were not indicated. - Per .]

Definition of a linear gradient insideensures that it will not be suddenly displayed on its own, only when used anywhere.

In the previous section, two flaws of the element were mentioned.:
  1. The position of the new element is set relative to the original.
  2. The styles of the source element cannot be overridden in copies.

Well, in addition, the source element is displayed by itself.

All of these drawbacks can be avoided by using. Not only does the original element not appear, but also when using the element defined inside, the position of each instance is set relative to the origin of the coordinate system.

In the following example, we will draw a tree [And think about binary! - Trans .]. It consists of a trunk and leaves. The leaves are collected in a group with id = "leaves", and together with the trunk they are included in a more general group with id = "tree".
Part of code drawing a tree

At the output, our tree will look something like this:

[Unfortunately, the code was shortened by the author, having lost most of the leaves. What is left reminds me of part of some alien industrial landscape. - Per .]

If you wrap the group #tree in an element, the tree will no longer be displayed.
More and more cut code

The tree now serves as a template. We can use it with an any other item. The only difference is that the x and y coordinates are relative to the origin.

Let's draw a mini forest as an example.


As you can see, each tree is located relative to the origin, for which, in this case, the upper left corner of the image is taken. Trees are located independently of each other and from the location in the template.

When reusing items defined in, you can apply separate styles for each tree until these styles are defined for the original template. If the tree is insideIf it has its own styles, then it will not be possible to redefine them. Thus,perfectly suited to determine the very foundation that will be used and painted if necessary. Using only without It would be impossible to achieve such flexibility.

Please note that the items inside are not displayed, that is, they behave exactly the same as the element with the property display = "none" set. However, the descendantsalways represented in the source tree [Speech on the SVG object tree, I guess. - Trans .], And other elements can always refer to them. Thus, the value of the display property of an element(or its descendants) does not prevent other elements from referencing it, even if this property is set to none.

[Not sure of the correct understanding of what the author wanted to say in this paragraph. I tried putting display = "none" for the element inside, and this element stopped displaying, which seems to be logical. Apparently, it’s aboutyou can set display = "none" and nothing will change. The following section describes this more clearly. Just in case, I will add a paragraph in the original. - Per .]

Previous paragraph in the original
Note that elements inside the element are prevented from becoming part of the rendering tree just as if the defs element were ag element and the display property were set to none. However, that the descendants of a defs are always present in the source tree and thus can always be referenced by other elements; thus, the value of the display property on the defs element or any of its descendants does not prevent those elements from being referenced by other elements, even if it is set to none.

Grouping items using

Element look like : It also provides the ability to group items. Two main differences can be distinguished:
  1. Element not displayed by itself. That makes him look like.
  2. Element may have its own attributes viewBox and preserveAspectRatio. This allows it to fit in the viewport (viewport) as you want, and not as defined by default.

In most cases Suitable for defining reusable elements (characters). It still serves as a template for. And having its own attributes viewBox and preserveAspectRatio, it can be stretched to the rectangular viewport specified in the element that refers to it. Note that the elements define a new viewport each time the item is called .

This is a great feature of the item.. It allows you to define elements that are independent of the viewport into which they fall. They will always be displayed in the specified way.

But to understand all this magic, you need to know how the viewBox and preserveAspectRatio attributes work in general. Chris Coyier has an article on this subject explaining why the element is so good.why it is a good choice for implementing icons and how to use it in general.

I have already written an extensive article about viewport, viewBox and preserveAspectRatio. Check out: Understanding SVG Coordinate Systems and Transformations (Part 1) - The viewport, viewBox, and preserveAspectRatio .

Keep in mind that the display property does not apply to an element.. Even if you set it other than display = "none", the item will still not be displayed. And at the same time, the element can be referenced even if he or his descendants have the display = "none" property set.


All of these elements are SVG structural containers, making it easy to reuse elements while making the code cleaner and clearer. Each of these elements has its own scope. Now, knowing what each of them does and how they differ from each other, you can decide which one to use depending on the situation.

I hope you enjoyed the article and found it useful. Thank you for reading!

From translator

The translation in some places is quite free, but not to the detriment of the meaning or content. Everything that is not directly related to the original is included in the notes. In the code, I made small edits in places, but this is either completely uncritical or noted in the notes.

With suggestions, wishes and comments, as usual, in the PM.

Also popular now: