Basic SVG document structure

Being written in Xml SVG document should have well-formed Xml structure. Therefore it is necessary to start with the standard Xml processing and to declare the document type (DOCTYPE) before any SVG code.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

Further the root <svg> element goes. The <svg> element defines the width and the height of the finished graphic (on default it is in pixels).

The <desc> and <title> elements are not rendered as part of the graphics in an SVG document. The <title> element's content is available to a viewing program and can be used in a title bar or as a tooltip pointer. The <desc> element lets you give a full description of the image.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="140" height="170">
<title>Sample</title>
<desc>Simple document structure example</desc>
<!-- the drawing is here -->
</svg>

The <svg> element can also be used within the middle of SVG content. It can be embedded inline as a fragment within a parent Xml document. Another way is to establish a new viewport. Here is an example:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="200" height="150">
<desc>This SVG drawing embeds another one, thus establishing a new viewport
</desc>
<svg x="25%" y="25%" width="50%" height="50%">
<!-- another drawing is here -->
</svg>
</svg>

For grouping together related graphics elements the <g> element is used. A group of elements can be given a name using the id attribute. Here is a simple example:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="200" height="150">
<desc>A simple example of <g> element
</desc>
<g id="group1">
<!-- here are different elements such as line, rect, circle, etc. -->
</g>
</svg>

When grouped, elements are formatted as if they were a single element (shape). This makes an advantage in using <g> element instead of <svg> element. But there is one disadvantage: <g> element doesn't have x and y attributes. And to move the contents you need to use the transform attribute.

Here is a simple example of using transform attribute with resulting images:

...
<g>
<rect x="10" y="10" width="100" height="50" fill="lightblue"/>
<circle cx="110" cy="60" r="30" fill="red"/>
<text x="10" y="60" font-size="16" fill="black"> grouped rectangle and circle
</text>
</g>
...
And now we apply the transform attribute to the group:
...
<g transform="rotate(20 100 75)">
<rect x="10" y="10" width="100" height="50" fill="lightblue"/>
<circle cx="110" cy="60" r="30" fill="red"/>
<text x="10" y="60" font-size="16" fill="black"> grouped rectangle and circle
</text>
</g>
...