AnSVG document fragment consists of any number of SVG elementscontained within an‘svg’ element.
An SVG document fragment can range from an empty fragment (i.e.,no content inside of the‘svg’ element), to a very simple SVGdocument fragment containing a single SVGgraphics elementsuch as a‘rect’, to a complex, deeply nested collection ofcontainer elements andgraphics elements.
An SVG document fragment can stand by itself as a self-containedfile or resource, in which case the SVG document fragment is anSVG document, or it can be embedded inline as a fragment within a parentHTML or XML document.
The following example shows simple SVGcontent embedded inline as a fragment within a parent XML document.Note the use of XML namespaces to indicate that the‘svg’ and‘ellipse’ elements belong to theSVG namespace:
<?xml version="1.0" standalone="yes"?><parent xmlns="http://example.org" xmlns:svg="http://www.w3.org/2000/svg"> <!-- parent contents here --> <svg:svg width="4cm" height="8cm"> <svg:ellipse cx="2cm" cy="4cm" rx="2cm" ry="1cm" /> </svg:svg> <!-- ... --></parent>
This example shows a slightly more complex (i.e., it containsmultiple rectangles) stand-alone, self-contained SVG document:
<?xml version="1.0" standalone="no"?><svg width="5cm" height="4cm" version="1.1" xmlns="http://www.w3.org/2000/svg"> <desc>Four separate rectangles </desc> <rect x="0.5cm" y="0.5cm" width="2cm" height="1cm"/> <rect x="0.5cm" y="2cm" width="1cm" height="1.5cm"/> <rect x="3cm" y="0.5cm" width="1.5cm" height="2cm"/> <rect x="3.5cm" y="3cm" width="1cm" height="0.5cm"/> <!-- Show outline of viewport using 'rect' element --> <rect x=".01cm" y=".01cm" width="4.98cm" height="3.98cm" fill="none" stroke="blue" stroke-width=".02cm" /></svg>
‘svg’ elements can appear in the middle of SVG content. Thisis the mechanism by which SVG document fragments can be embedded withinother SVG document fragments.
Another use for‘svg’ elements within the middleof SVG content is to establish a new SVG viewport. (SeeEstablishing a newSVG viewport.)
When SVG is parsed as a XML, for compliance with theNamespaces in XML Recommendation[xml-names], an SVG namespacedeclaration must be provided so that all SVG elements are identifiedas belonging to the SVG namespace.
When using the HTML syntax, the namespace is provided automatically by the HTML parser.
<html><svg viewBox="0 0 100 100"> <circle cx="50" cy="50" r="50" fill="green"></svg></html>
As the example shows there's no need to have an‘xmlns’ attribute declaring that the element is in the SVG namespace when using the HTML parser. The HTML parser will automatically create the SVG elements in the proper namespace.
This section should talk about how a document's behavioris defined in terms of the DOM, and also explain how the HTML parser cancreate SVG fragments.
The SVG 2 namespace ishttp://www.w3.org/2000/svg
,which is the same as for earlier versions of SVG.
The following are possible ways toprovide a namespace declaration when SVG is parsed as XML. An‘xmlns’attribute without a namespace prefix could be specified on an‘svg’ element, which means that SVG is the default namespacefor all elements within the scope of the element with the‘xmlns’ attribute:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <rect x="10" y="10" width="80" height="80" fill="green" /></svg>
If a namespace prefix is specified on the‘xmlns’attribute (e.g.,xmlns:svg="http://www.w3.org/2000/svg"
),then the corresponding namespace is not the default namespace, so anexplicit namespace prefix must be assigned to the elements:
<svg:svg xmlns:svg="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <svg:rect x="10" y="10" width="80" height="80" fill="green" /></svg:svg>
Namespace prefixes can be specified on ancestor elements (illustratedin theabove example). For moreinformation, refer to theNamespaces in XML Recommendation[xml-names].
SVG 2 Requirement: | Support transforming‘svg’ elements. |
---|---|
Resolution: | We will allow‘transform’ on‘svg’ in SVG 2. |
Purpose: | To allow transforms on nested‘svg’ elements, in line with author expectations. |
Owner: | Dirk (no action) |
Status: | Done |
Thex andy attributes specify the top-left corner of the rectangular region into which an embedded‘svg’ element is placed. On anoutermost svg element, these attributes have no effect.
Foroutermost svg elements, thewidth andheight attributes specify the intrinsic size of the SVG document fragment. For embedded‘svg’ elements, they specify the size of the rectangular region into which the‘svg’ element is placed. In either case, a computed style ofauto is treated equivalent to100%.
Attribute definitions:
Name | Value | Initial value | Animatable |
---|---|---|---|
zoomAndPan | disable | magnify | magnify | no |
Specifies whether the user agent should supply a means to zoom and pan the SVG content. See the definition of‘zoomAndPan’ for details.
If an SVG document is likely to be referenced as a componentof another document, the author will often want to include a‘viewBox’ attribute on theoutermost svg element of thereferenced document. This attribute provides a convenient way to designSVG documents to scale-to-fit into an arbitrary SVG viewport.
The‘svg’ element exposes asevent handler content attributes a number of theevent handlers of theWindow object. It also mirrors theirevent handler IDL attributes.
Theonblur,‘onerror’,onfocus,‘onload’, and‘onscroll’event handlers of theWindow object, exposed on the‘svg’ element,replace the genericevent handlers with the same names normally supported bySVG elements.
The‘g’ element is acontainer element for grouping togetherrelatedgraphics elements.
A group of elements, as well as individual objects, can be givena name using the‘id’ attribute. Named groups are needed forseveral purposes such as animation and re-usable objects.
An example:
<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="5cm" height="5cm"> <desc>Two groups, each of two rectangles</desc> <g fill="red"> <rect x="1cm" y="1cm" width="1cm" height="1cm"/> <rect x="3cm" y="1cm" width="1cm" height="1cm"/> </g> <g fill="blue"> <rect x="1cm" y="3cm" width="1cm" height="1cm"/> <rect x="3cm" y="3cm" width="1cm" height="1cm"/> </g> <!-- Show outline of viewport using 'rect' element --> <rect x=".01cm" y=".01cm" width="4.98cm" height="4.98cm" fill="none" stroke="blue" stroke-width=".02cm"/></svg>
A‘g’ element can contain other‘g’ elements nestedwithin it, to an arbitrary depth.
SVG 2 Requirement: | Have unknown elements treated as‘g’ for the purpose of rendering. |
---|---|
Resolution: | |
Purpose: | To allow fallbacks without the use of‘switch’, and to align with the behavior of unknown elements in HTML. |
Owner: | Nobody (no action) |
Status: |
Treating unknown elements as a generic container element, resulting in therendering of their child trees, and assigning the SVGUnknownElement interface tounknown elements are both at risk, with no known implementations.
Unknown elements are all elements that are in the SVG namespace that are notdefined by this specification or any SVG module. TheSVGUnknownElementinterface must be used for unknown elements.
Unknown elements in the SVG namespace arerenderable elements andcontainer elements.They must render as if the unknown elementwere replaced with a‘g’ element or‘tspan’, according to context.Any global attribute or property that is valid on any SVG graphics elementis also valid on unknown elements, and must be processed as normal.This includes conditional processing attributes, ARIA attributes, data attributes,and the‘lang’,‘id’,‘class’,‘tabindex’ and‘style’.Styles specified on unknown elements must be inherited bytheir child elements according to the normal rules for inheritance for each style property.
Known and unknown elements in other namespaces that occur as a child of anySVG element except‘foreignObject’, must not render unlessexplicitly stated otherwise in this specification.
Known elements in the SVG namespace that occur in places where SVG's contentmodel doesn't explicitly allow it must not render unlessexplicitly stated otherwise in this specification.
Consequently, in the following example:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 700 200"> <rect x=".1" y=".1" width="699.8" height="199.8" fill="none" stroke="blue" stroke-width=".2" /> <mysteryElement> <path d="M0 0h600v200h-600z" fill="darkkhaki"/> </mysteryElement> <hideElement xmlns="http://www.example.com/invisibleML"> nothing to see here <path d="M0 0h300v100h-300z" fill="whitesmoke"/> </hideElement> <text y="2em" font-size="20"><text>This text must not be visible</text></text> <linearGradient> <gradientExtension> <path d="M300 0h100v200h-100z" fill="fuchsia"/> </gradientExtension> </linearGradient> <div xmlns="http://www.w3.org/1999/xhtml">This must not be visible</div></svg>
SVG allows a graphical object to be defined for later reuse.To do this, SVG makes extensive use of theURL referenceconstruct [rfc3987].For example, to fill a rectangle with a linear gradient, a‘linearGradient’ element may be defined with an‘id’ property that may be referenced in the value forthe rectangle'sfill property, as in the following:
<linearGradient>...</linearGradient><rect/>
Some types of element, such as gradients, will not by themselves produce a graphical result. They can therefore be placed anywhere convenient. However, sometimes it is desired to define a graphical object and prevent it from being directly rendered. it is only there to be referenced elsewhere. To do this, and to allow convenient grouping defined content, SVG provides the‘defs’ element.
It is recommended that, where possible, referenced elements be definedprior to the elements that use them, in document order.Collecting all referenced elementsinside of a single‘defs’ elementnear the top of the filecan make the markup easier to read and understand.
The‘defs’ element is a container element forreferenced elements. For understandability andaccessibility reasons, it is recommendedthat, whenever possible, referenced elements be defined insideof a‘defs’.
The content model for‘defs’ is the same as for the‘g’ element; thus, any element that can be a child of a‘g’ can also be a child of a‘defs’, and vice versa.
Elements that are descendants of a‘defs’ are not rendered directly;thedisplay value for the‘defs’ elementmust always be set tononeby theuser agent style sheet,and this declaration must have importance over any other CSS rule or presentation attribute.Note, however, that the descendants of a‘defs’ arealways present in the source tree and thus can always bereferenced by other elements; thus, the value of thedisplayproperty on the‘defs’ element does notprevent those elements from being referenced by other elements.
The‘symbol’ element is used to define graphical templateswhich can be instantiated by a‘use’ element but which are not rendereddirectly.
A‘symbol’ establishes a nested coordinate system for the graphics it contains. When a symbol is instantiated as thereferenced element of a‘use’ element, it is therefore rendered very similarly to a nested‘svg’ element.
Thex,y,width, andheight geometry properties have the same effect as on an‘svg’ element, when the‘symbol’ is instantiated by a‘use’ element. In particular, ifwidth andheight compute toauto (and are not over-ridden by values on the instantiating‘use’ element), then they will be treated as a value of100%.
New in SVG 2. Allowing geometry properties to be specified on a symbol provides a more consistent rendering model, and allows authors to set a default size for each symbol (which may still be over-ridden by attributes on the‘use’ element).
Name | Value | Initial value | Animatable |
---|---|---|---|
refX | <length> | left | center | right | (none) | yes |
refY | <length> | top | center | bottom | (none) | yes |
New in SVG 2. Added to make it easier to align symbols to a particular point, as is often done in maps. Similar to the matching attributes on‘marker’.
Add refX/refY to symbol element. Resolved atLeipzig F2F. Status: Done.
We will add top/center/bottom, left/center/right keywords to refX/refY on marker/symbol. Resolved atLondon F2F. Values inspired by'background-position'. Status: Done.
The‘refX’ and‘refY’ attributes define the reference point of the symbol which is to be placed exactly at the symbol'sx,y positioning coordinate, as defined by the cumulative effect of thex andy properties and any transformations on the‘symbol’ and itshost‘use’ element.
Keyword values have the same meaning as for the‘refX’ and‘refY’ attributes on the‘marker’ element, resolving to 0%, 50%, or 100% in the applicable direction.
Unlike other positioning attributes,‘refX’ and‘refY’ are interpreted as being in the coordinate system of the symbol contents, after application of the‘viewBox’ and‘preserveAspectRatio’ attributes. If one or both of the attributes is not specified, no adjustment is made in the corresponding dimension, and the top or left side of the symbol's rectangular viewport region (regardless of the‘viewBox’ coordinates) is positioned at thex,y point.
For backwards compatibility, the behavior when‘refX’ and‘refY’ are not specified on a‘symbol’ is different from when they are specified with a value of0, and therefore different from the behavior when equivalent attributes are not specified on a‘marker’.
The use of‘symbol’ elements for graphics that are used multipletimes in the same document adds structure and semantics.Closely related to the‘symbol’ element are the‘marker’ and‘pattern’ elements;all three define a container of graphical contentthat can be rendered repeatedly at various positions and scales in the SVG.However, whilere-used graphics in a pattern and markerprovide a graphical effect on another element,the content in a‘symbol’ will be embeddedas fully interactive content, within ause-element shadow tree.
Theuser agent style sheet setstheoverflow property for‘symbol’ elements tohidden, which causes a rectangular clippingpath to be created at the bounds of symbol's SVG viewport. Unless theoverflow property is overridden, any graphics within the symbol whichgoes outside of the symbol's SVG viewport will be clipped.
‘symbol’ elements must never be rendered directly;their only usage is as something that can be referencedusing the‘use’ element.The user agent must set thedisplay property on the‘symbol’ elementtonone,as part of theuser agent style sheet,and this declaration must have importance over any other CSS rule or presentation attribute.
The generatedinstance of a‘symbol’that is the directreferenced element of a‘use’ elementmust always have a computed value ofinlinefor thedisplay property.In other words, it must be rendered whenever the host‘use’ element is rendered.Theuser agent style sheet again defines thisdeclaration to have importance over any other CSS rule or presentation attribute.Any other‘symbol’ that is clonedto create anelement instancewithin theuse-element shadow treebehaves as a symbol definition, and must not be rendered.
SVG 2 Requirement: | Allow‘use’ to reference an external document's root element by omitting the fragment. |
---|---|
Resolution: | We will relax referencing requirements to particular elements to allow dropping fragments to mean referencing root element, where it makes sense, such as with use, in SVG 2. |
Purpose: | To avoid requiring authors to modify the referenced document to add an ID to the root element. |
Owner: | Cameron (ACTION-3417) |
Status: | Done |
The‘use’ elementreferences another element, a copy of whichis rendered in place of the‘use’ in the document.Thereferenced element may be acontainer element,in which case a copy ofthe complete SVG document subtree rooted at that element is used.
The cloned content inherits styles from the‘use’ elementand can be the target of user events.However, these clonedelement instances remain linked to the referenced sourceand reflect DOM mutations in the original.In addition, all style rules that apply in the scope of the referenced elementalso apply in the scope of the clonedshadow tree.
Thex,y,width andheight geometric properties specify the positioning of the referenced element. Thewidth andheight attributes only have an effect if thereferenced element defines a viewport (i.e., if it is a‘svg’ or‘symbol’); if so, a value other thanauto for the‘use’ element overrides the value of the corresponding geometric property on that element.
A negative value forwidth orheight must be treated as an illegal value. Ifwidth orheight is zero, and the properties have an effect on thereferenced element, then rendering of that element will be disabled.
Thex andy properties affect the user coordinate system for the element. See theLayout section for implementation details.
Name | Value | Initial value | Animatable |
---|---|---|---|
href | URL[URL] | (none) | yes |
AnURL reference to the element/fragment within an SVG document to be cloned for rendering.
The‘use’ element can reference an entire SVG document by specifying an‘href’ value without a fragment. Such references are taken to be referring to the root element of the referenced document.
Refer to the common handling defined forURL reference attributes anddeprecated XLink attributes.New in SVG 2.An‘href’ without a fragment allows an entire SVG document to be referencedwithout having to ensure that it has an ID on its root element.
User agents may restrict external resource documents for securityreasons. In particular, this specification does not allow cross-origin resource requests in‘use’.A future version of this or another specification may provide a method of securely enabling cross-origin re-useof assets.
When the‘href’ attribute is set(or, in the absence of an‘href’ attribute, an‘xlink:href’ attribute),the user agent mustprocess the URL.The target element that results from URL processing is thereferenced element of the‘use’.
If thereferenced element that results from resolving the URL is neither an SVG element nor an HTML-namespaced elementthat may be included as a child of an SVG container element, then the reference isinvalid and the‘use’ element is in error.
If the referenced element is a (shadow-including) ancestor of the‘use’ element, then this is aninvalid circular reference and the‘use’ element is in error.
Otherwise, the user agent must generate ashadow tree ofre-used graphics to render as the contents of the‘use’ element, as described in the next section,The use-element shadow tree.
A‘use’ that has anunresolved orinvalid URL reference is not rendered. For the purpose of bounding box calculations, it is equivalent to an empty container element.
There-used graphics generated by a‘use’ elementare defined in terms of ashadow tree.In terms of interactivity and style inheritance,they are therefore quite different from other types ofre-used graphics in SVG,such as‘pattern’ and‘marker’ content.
Elements in the shadow tree are rendered as ifthe‘use’ element was a container and they were its children.However, the SVG Document Object Model (DOM) only containsthe‘use’ element and its attributes.The SVG DOM does not include theelement instances as children of the‘use’ element.
User agents that support scripting and the document object modelmust implement theuse-element shadow tree as described in this sectionand in conformance with thedom specification[dom],or its future replacement.In contrast, user agents that donot supportthe dynamic interactive processing modemay not need to implement all the details of the shadow DOM.However, all user agents must ensure that thelayoutandstyle inheritance for the re-used graphics,and anymultimediaanddeclarative animations if applicable,are rendered in the same way as if the shadow DOM was implemented.
The following definitions apply when discussing‘use’ elements and their shadow trees:
When the user agent successfully resolves a‘use’ elementto identify areferenced element,the user agent must create ause-element shadow tree whose host is the‘use’ element itself.The shadow tree must be created even ifthe‘use’ element is not renderedbecause it is a descendent of anever-rendered element,because of conditional processing,or because of thedisplay property being set tononeon it or an ancestor element.
Each node in the shadow tree is aninstance of a corresponding nodefrom thereferenced document subtree.The shadow nodes all descend from theinstance root,which is the instance of thereferenced element,and which itself is a direct child of theshadow root node.
The shadow tree is open (inspectable by script), but read-only.Any attempt to directly modify the elements, attributes, and other nodes in the shadow treemust throw aNoModificationAllowedError
.
Within ause-element shadow tree,‘script’ elements are inert (do not execute);‘audio’ and‘video’ elementsare subject to the limitations specified in theMultimedia section.
Previous versions of SVG restricted the contents of the shadow tree to SVG graphics elements. This specification allows any valid SVG document subtree to be cloned. Cloning non-graphical content, however, will not usually have any visible effect.
If thereferenced element is in an external file,then allURL references in attributes and style propertiesmust be made absolute as described inGenerating the absolute URL,before copying the value to theelement instances.The shadow tree itself uses the same document base URLas the document that includes it.
The user agent must ensure thatall mutations to thereferenced document subtree are reflected in the shadow tree.This includes changes to elements, attributes, and text and other nodes.In addition, changes to the stylesheets in effect for the referenced graphicsmust be reflected in changes to the stylesheets in the shadow tree's scope,as described futher in the section onstyle inheritance.
If either the‘use’ element or thereferenced element is alteredin a way that causes the‘use’ element's URL reference to becomeunresolved again,then the entire shadow tree for that use element is discarded.
When a‘use’ referencesanother element which is another‘use’ or whose content contains a‘use’ element, then the shadow DOMcloning approach described above is recursive. However, a setof references that directly or indirectly reference a elementto create a circular dependency is aninvalid circular reference.The‘use’ element or element instancewhose shadow tree would create the circular referenceis in error and must not be rendered by the user agent.
The value of thex,y,width andheight propertieson a‘use’ elementare used to position the re-used graphicsand to set the viewport sizeif thereferenced element defines a nested viewport.The effect of these properties on a‘use’ elementis notably different from their effect on agraphics element,or from their effect in CSS box layout.
Thex andy properties define an additional transformation (translate(x,y), wherex andy represent the computed value of the corresponding property) to be applied to the‘use’ element, after any transformations specified with other properties (i.e., appended to the right-side of the transformation list).
For historical reasons, the supplemental transformation is applied to the‘use’ element itself, rather than solely to the re-used content in the shadow tree. This affects the coordinate system used for any masks, clipping paths, or filters applied to the‘use’ element and calculated inuserSpaceOnUse units.
To applyuserSpaceOnUse graphical effects in an un-transformed coordinate space, while also using thex andy to position the graphics, authors can nest the‘use’ element inside a‘g’, and apply the graphical effects to the‘g’ element.
Thewidth andheight properties on the‘use’ element override the values for the corresponding properties on a referenced‘svg’ or‘symbol’ element when determining the used value for that property on theinstance root element. However, if the computed value for the property on the‘use’ element isauto, then the property is computed as normal for the element instance.
These properties can therefore be used to scale a graphic that defines its own coordinate system, each time it is re-used. Becauseauto is the initial value, if dimensions are not explicitly set on the‘use’ element, the values set on the‘svg’ or‘symbol’ will be used as defaults.
Thewidth andheight properties on the‘use’ element have no effect if thereferenced element does notestablish a new viewport. In particular, the‘use’ element does not itself establish a new viewport, and therefore does not affect the interpretation of percentages in the re-used graphics.
In all other ways, rendering and layout of elements within theuse-element shadow tree occurs as if the‘use’ element was a container for its shadow content. In particular, unless elements within the shadow tree establish a new viewport, they must be drawn in the coordinate system in which the‘use’ element is defined (including any cumulative transformations). This affects the interpretation of percentage lengths, and also graphical effects withuserSpaceOnUse units.
Theuse-element shadow tree, like other shadow trees, exhibits style encapsulation, as defined in theCSS Scoping module[css-scoping-1]. This means that elements in the shadow tree inherit styles from itshost‘use’ element, but that style rules defined in the outer document do not match the elements in the shadow tree. Instead, the shadow tree maintains its own list of stylesheets, whose CSS rules are matched against elements in the shadow tree.
Presentation attributes and the‘style’ attribute are cloned from the elements in thereferenced graphics into theelement instances in the same manner as other attributes.
When thereferenced element is from the same document as the‘use’ element, the same document stylesheets will apply in both the original document and the shadow tree document fragment. Any changes to the stylesheets in the main document also affect the shadow tree; theStyleSheetList
object accessed through the document and shadow root document fragment'sstyleSheets
properties must be identical. If a‘style’ element is duplicated as part of thereferenced document subtree, then thestyleSheet
property on theelement instance points to the same object as for thecorresponding element.
When thereferenced element is from an external document, the stylesheet objects generated when processing that document apply to the shadow tree, and are read-only. AllURL references in the stylesheet, including fragment-only references, must be made absolute, relative to the URL of the document that contains thereferenced element. User agents may re-use the same stylesheet objects for any shadow trees that reference that same external document.
Style rules that are scoped to the shadow tree cannot normally affect any elements in the main document. Similarly, style rules in the main document can only affect the shadow tree elements by changing inherited values. However,CSS Scoping defines special selectors for styling thehost element from within the shadow tree, or for adjusting styles within the shadow tree in response to changes in the host's context[css-scoping-1].
CSS media queries within a shadow tree's scope are evaluated using the same device features and dimensions as the corresponding "light" document (that is, the document that contains thecorresponding use element for the shadow tree, after recursively exiting all nested shadow trees).
In most cases, theelement instance in the shadow tree will match the same style rules as itscorresponding element in the original document. However, if a CSS rule uses acomplex selector to match an element based on its ancestors or siblings, and those ancestors or siblings are not cloned as part of the shadow tree, then that rule would no longer match theelement instance. Similarly, child-indexed pseudo-classes such asnth-of-type
andnth-child
may apply to one element but not the other. This represents a change from how style cloning was defined in previous versions of SVG.
The following example demonstrates both the consistent and changed style-matching rules. The circle on the left is re-used to draw the circle on the right. The original circle has styles set in various ways:
special
.In the SVG 1.1 style-cloning model, thespecified style values would be cloned from the original element to the element instance. The re-used circle would have the same styles as the original, except that thefill value would be inherited from the‘use’ (orange) instead of from the‘g’ (blue).
In the shadow DOM model required by SVG 2, the styles for the re-used circle are calculated as follows:
special
; instead,stroke color on the circle is inherited from the host‘use’ element (purple).The re-used circle therefore differs from the original in both fill color (because it inherits from a different element) and stroke color (because the complex selector no longer matches).
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="100" viewBox="0 0 200 100"> <title>Style inheritance and the use element</title> <desc> Two circles, one of which is a re-styled clone of the other. This file demonstrates one of the cases where the shadow-DOM style matching rules in SVG 2 have a different effect than the SVG 1.1 style cloning rules. The original circle on the left should have blue fill and green stroke. In a conforming SVG 1.1 user agent, the re-used circle on the right should have orange fill and green stroke. In a conforming SVG 2 user agent, the re-used circle should have orange fill and purple stroke. In all cases, the stroke should be partially transparent and 20 units wide, relative to a total circle diameter of 100 units. </desc> <style type="text/css"> circle { stroke-opacity: 0.7; } .special circle { stroke: green; } use { stroke: purple; fill: orange; } </style> <g> <circle cy="50" cx="50" r="40" stroke-width="20" /> </g> <use xlink:href="#c" x="100" /></svg>
Example Use-changed-styles
Previous versions of SVG were not clear about how dynamic pseudo-classes (such as:hover
) should apply to element instances. The shadow tree model requires that all such pseudo-classes are matched independently to theelement instance or to itscorresponding element, depending on which element the user is interacting with.
Specifying'visibility:hidden' on a‘use’ element does not guarantee that the referenced content will not be rendered. Unlike thedisplay or theopacity properties, thevisibility property does not appy directly to container elements, and therefore does not apply directly to the‘use’ element. Becausevisibility is normally inherited, hiding the use element will often hide the child content, but not necessarily. If any graphics elements in the shadow tree have'visibility:visible' specified, then that element will be visible even if the‘use’ element specifies'visibility:hidden'.
In the following example, key style rules are as follows:
.dark { visibility: hidden;}.eyes { visibility: visible;}svg:hover .dark, svg:focus .dark { visibility: visible;}
The "dark" class is set on the group containing the‘use’ elements, so all parts of the re-used graphics inherit the hidden visibility setting, except for the subtrees with class "eyes", where it is reset to visible. Upon hovering or focusing the graphic, the hiding effect is removed.
Example Use-visibility-hidden, default styles
Example Use-visibility-hidden, interactive styles
The example also demonstrates inheritance of other style properties (fill andstroke) specified on the‘use’ elements, and how these are also not used if any elements within the symbol specify explicit values (e.g., the pink noses and ears and the white tails).
When ause-element shadow tree includes‘audio’ or‘video’ elements, the following behaviors must be enforced:
TheWeb Animations API [web-animations-1] and theSVG Animations specification [svg-animation] define non-CSS ways to animate attributes and styles on targetted elements without directly manipulating DOM properties (see theAnimation appendix for details). User agents that implement those features must ensure that all animations that apply to an element in areferenced document subtree also apply to instances of that element in ause-element shadow tree, as described in this section.
Scripted animations created by directly manipulating attributes on elements in thereferenced graphics (including the‘style’ attribute or its IDL property) will be propagated to theelement instances in the shadow tree in the same manner as any other DOM manipulations.
Animation effects applied using CSS will be duplicated along with other stylesheet rules, following the procedure specified in theStyle Scoping and Inheritance section.
All animations within ause-element shadow tree operate in the same document timeline as for thecorresponding use element, regardless of whether thereferenced element is from the same or an external document.
For animation effects applied using aWeb Animations API method[web-animations-1], if the target of the animation is acorresponding element to anelement instance in a shadow tree, the user agent must construct aShadowAnimation whose source is thatAnimation object and whose target is theelement instance. If there are multiple instances of the element in different trees, then there will be multiple shadow animations, one for each.
The user agent must create such aShadowAnimation for all Web Animations API animations in effect (including pending and frozen animations) at the time the shadow tree is generated, and for any new animations applied while the shadow tree exists. The user agent must not createShadowAnimation objects for CSS animations or animation elements (as these are duplicated separately).
As part of the interface definition, aShadowAnimation is read-only, and must reflect any changes to itssourceAnimation.
Any attempts to directly apply new animations to a target that is a read-onlyelement instance (or pseudo-element) within ause-element shadow tree must throw aNoModificationAllowedError
.
For eachanimation element [svg-animation] that targets an element in thereferenced document subtree, the user agent must ensure that an equivalent animation element is in effect in theuse-element shadow tree. If the animation element itself is part of the referenced document subtree, then this happens as a matter of course through the creation of anelement instance for the animation element. Otherwise, the user agent must generate anelement instance for the animation element that has the same effect as if it was a node in the shadow tree. The effective document order for these generated animation elements must be the same as the document order for theircorresponding elements.
Each animation element or instance must only affect a target element in the same node tree (shadow or light), regardless of whether the targetting is implicit (the parent element) or explicit (a URL cross-reference to an element‘id’). In this way, the one-to-one relationship between animation elements and target elements is preserved.
The‘id’ attribute is cloned, like any other attribute, from thecorresponding element to theelement instance; This does not conflict with the requirement for‘id’ to be unique, because the clone and the original are in distinct node trees.
All animation elements, in the document or in the shadow trees, which are timed to begin or end in response to an event on another element identified by its‘id’ attribute, must also begin or end when anyinstance of an element with that‘id’ receives the same event. This is consistent with how event listeners on a referenced element also listen to events on instances of that element, as described in the section onEvent handling in use-element shadow trees. This behavior does not apply to animation begin or end times defined only by an event and not by an‘id’ (and therefore implicitly listening for the event on the target element); in that case, each animation element is only triggered by its own target.
At the time aninstance of an animation element is generated within a shadow tree, if there is an active animation associated with thecorresponding element (including a frozen animation), and the timing event that initiated that animation would also have initiated the instance if it existed, then the animation for theelement instance must be initiated, with its begin time adjusted backwards in the document timeline to match the timing of thecorresponding element.
In many cases, the requirements of this section mean that theelement instance and itscorresponding element will animate synchronously. This will be the case if the animation is purely time-based, or if it begins and ends in response to user interaction on an element referenced by its‘id’. However, if the animation is triggered by a user interaction event on the targetted element (implicitly), then only the element or element instance that receives the interaction event will display the animation.
This is a change from previous versions of SVG, which required all animations on thecorresponding element to be mirrored, regardless of user interaction, but which did not offer clear guidance for responding to user interactions with the element instances. The change ensures that interactive animations declared with animation elements behave in the same manner as interactive CSS styles and CSS animations.
In order to create animations that apply to all instances when any instance or the original element receives an event, specify the element‘id’ explicitly:
<set href="#target" begin="mouseover" ... /> <!-- only affects the element that is moused over --><set href="#target" begin="target.mouseover" ... /> <!-- affects all instances of the element with the id 'target', in all light and shadow node trees, when any of them are moused over -->
Element in ause-element shadow tree can both listen for and be the target of DOM events. Event retargetting provides encapsulation, so that the details of the shadow DOM structure are masked when an event bubbles out of the shadow tree and into the light.
Event retargeting is new in SVG 2. It provides consistency with the Shadow DOM specification, with existing implementations, and with the expectations of authors who are only concerned with elements in the main DOM.
Any event listeners defined on an element in thereferenced graphics must also listen for the same event, at the same capture phase, on eachinstance of that element in ause-element shadow tree. This includes event listeners assigned usingevent attributes (which would be duplicated as with any other DOM attribute) and also event listeners assigned using theaddEventListener
method. The user agent must ensure that the list of event listeners for eachelement instance is synchronized to match itscorresponding element. An event listener cannot be directly assigned to a read-onlyelement instance in ause-element shadow tree. Any attempt to add an event listener to such an element must throw aNoModificationAllowedError
.
Events in theuse-element shadow tree are dispatched and bubble according to the shadow treeevent path and event retargeting algorithm [DOM].
In general, the event path for ause-element shadow tree is constructed from the ancestors of the event target element up to theshadow root, then thehost‘use’ element and its event path through to the document window. This means that, in the capture phase, an event propagates from the window through the regular document tree to the‘use’ element and then to the shadow root object and down through the shadow tree (or recursively through multiple shadow trees) to the event target element. In the bubbling phase, the event passes in the opposite direction, from the shadow tree elements to the shadow root, then to the‘use’ element and its ancestors.
The event retargeting algorithm ensures that from the perspective of event listeners on the‘use’ element or its ancestors, all events targetted toelement instances in the shadow tree instead have a target of the‘use’ element itself. If the event has both atarget
and arelatedTarget
, and both of these properties would be retargeted to point to the same‘use’ element, then the event is not propagated at all outside of the shadow tree. This would occur, for example, if focus moved from one element inside the shadow tree to another. Certain other event types are constrained to not propagate outside of the shadow tree in which they were created.
In contrast, event listeners that process the event while it is propagating through the shadow tree (because the listener has been added to acorresponding element) will receive the event with itstarget
pointing to a read-onlyelement instance in the shadow tree. ThecorrespondingElement andcorrespondingUseElement properties of thatelement instance can be used to connect it to the modifiable elements in the main DOM.
SVG contains a‘switch’ element along withattributes‘requiredExtensions’ and‘systemLanguage’ to provide anability to specify alternate viewing depending on thecapabilities of a given user agent or the user's language.
Attributes‘requiredExtensions’ and‘systemLanguage’ act as tests andevaluate to either true or false. The‘switch’ renders the first ofits children for which all of these attributes test true. Ifthe given attribute is not specified, then a true value isassumed.
When an element is excluded because of conditional processing,it is treated as if it had a used value ofnone
for thedisplay property.Similar to thedisplay property, conditional processingattributes only affect the direct rendering of elements and donot prevent elements from being successfully referenced byother elements (such as via a‘use’).
In consequence:
Previous versions of SVG included a third conditional processing attribute,requiredFeatures
. This was intended to allow authors to provide fallback behavior for user agents that only implemented parts of the SVG specification. Unfortunately, poor specification and implementation of this attribute made it unreliable as a test of feature support.
The‘switch’ element evaluatesthe‘requiredExtensions’ and‘systemLanguage’ attributes on its direct child elements inorder, and then processes and renders the first child for which theseattributes evaluate to true. All others will be bypassed and thereforenot rendered. If the child element is a container element such as a‘g’, then the entire subtree is either processed/rendered orbypassed/not rendered.
In SVG, when evaluating the‘systemLanguage’ attribute, the order ofevaluation of descendant elements of the‘switch’ element must be as if the'allowReorder'attribute, defined in the SMIL specification [SMIL]always has a value of 'yes'.
Note that the values of propertiesdisplay andvisibility have no effect on‘switch’ elementprocessing. In particular, settingdisplay tonone on a child of a‘switch’ elementhas no effect on true/false testing associated with‘switch’element processing.
The‘switch’ element does not affect the processing of‘script’ and‘style’ elements.
For more information and an example, seeEmbedding foreignobject types.
The‘requiredExtensions’attribute defines a list of required language extensions.Language extensions are capabilities within a user agent thatgo beyond the feature set defined in this specification. Eachextension is identified by anURL reference.
Name | Value | Initial value | Animatable |
---|---|---|---|
requiredExtensions | set of space-separated tokens[HTML] | (none) | no |
The value is a list ofURL references which identify the required extensions, with the individual values separated by white space. Determines whether all of the namedextensions are supported by the user agent. If all of the given extensions are supported, then the attribute evaluates to true; otherwise, the current element and its children are skipped and thus will not be rendered.
If a givenURLreference contains white space within itself, that whitespace must be escaped.
If the attribute is not present, then it implicitly evaluates to "true". If a null string or empty string value isgiven to attribute‘requiredExtensions’, the attributeevaluates to "false".
‘requiredExtensions’ is oftenused in conjunction with the‘switch’ element. If the‘requiredExtensions’ is used in othersituations, then it represents a simple switch on the givenelement whether to render the element or not.
The URL names for the extension should include versioninginformation, such as "http://example.org/SVGExtensionXYZ/1.0",so that script writers can distinguish between differentversions of a given extension.
Name | Value | Initial value | Animatable |
---|---|---|---|
systemLanguage | set of comma-separated tokens[HTML] | (none) | no |
The value is aset of comma-separated tokens, each of which must be aLanguage-Tag value, as defined inBCP 47 [BCP47].
Evaluates to "true" if one of the language tags indicated byuser preferences is a case-insensitive match of one of the language tags given inthe value of this parameter, or if one of the language tagsindicated by user preferences is a case-insensitive prefix of one ofthe language tags given in the value of this parameter such thatthe first tag character following the prefix is "-".
Evaluates to "false" otherwise.
If the attribute is not present, then it implicitly evaluates to "true".If a null string or empty string value isgiven to attribute‘systemLanguage’, the attribute evaluates to"false".
Note: This use of a prefix matching rule does not imply thatlanguage tags are assigned to languages in such a way that itis always true that if a user understands a language with acertain tag, then this user will also understand all languageswith tags for which this tag is a prefix.
The prefix rule simply allows the use of prefix tags if thisis the case.
Implementation note: When making the choice of linguisticpreference available to the user, implementers should take intoaccount the fact that users are not familiar with the detailsof language matching as described above, and should provideappropriate guidance. As an example, users may assume that onselecting "en-gb", they will be served any kind of Englishdocument if British English is not available. The userinterface for setting user preferences should guide the user toadd "en" to get the best matching behavior.
Multiple languages may be listed for content that isintended for multiple audiences. For example, content that ispresented simultaneously in the original Maori and Englishversions, would call for:
<text systemLanguage="mi, en"><!-- content goes here --></text>
However, just because multiple languages are present withinthe object on which the‘systemLanguage’ testattribute is placed, this does not mean that it is intended formultiple linguistic audiences. An example would be a beginner'slanguage primer, such as "A First Lesson in Latin," which isclearly intended to be used by an English-literate audience. Inthis case, the‘systemLanguage’ test attributeshould only include "en".
Authoring note: Authors should realize that if severalalternative language objects are enclosed in a‘switch’, and none of themmatches, this may lead to situations where no content isdisplayed. It is thus recommended to include a "catch-all"choice at the end of such a‘switch’ which is acceptable inall cases.
‘systemLanguage’ is often usedin conjunction with the‘switch’ element. If the‘systemLanguage’ is used in othersituations, then it represents a simple switch on the givenelement whether to render the element or not.
Multilingual descriptive text selection, based on the‘lang’ attribute, was added to allow internationalizationof the‘desc’ and‘title’ elements.
New in SVG 2. Adding 'lang' resolved at Rigi Kaltbad face-to-face.Removed text that limited number of 'desc' and 'title' elements. Status: Done.
Anycontainer element orgraphics element in an SVG documentcan have zero or more‘desc’ and/or‘title’ elements as children,whose content is text.‘desc’ and‘title’ elements arenot visually rendered as part of the graphics.Thedisplay value for the‘title’ and‘desc’ elementsmust always be set tononeby theuser agent style sheet,and this declaration must have importance over any other CSS rule or presentation attribute.
Multiple sibling‘desc’ or‘title’ elements must havedifferent languages,as defined using a‘lang’ attribute (orxml:lang
attribute) on the descriptive element or an ancestor.The user agent must select the element of each type whose language bestmatches language preferences set by the user.A descriptive element with an empty-string language tag(indicating no language, for example a text alternative consisting of emoji symbols)is a lowest-priority match for any user, ranked below all user-specified language preferences.If multiple equally valid matches exist, the first match should be used.If no match exists for either 'title' or 'desc', the first element of that type must be selected.
The following example shows alternative language titles on a re-used star icon, inline in an HTML document. The example assumes that the HTML document as a whole has a correctly-declared language ofen
(English without a specified country code).
<svg> <use href="#star"> <title>Favourite</title> <title lang="en-us">Favorite</title> <title lang="nl">Favoriet</title> <title lang="">★</title> </use></svg>
The firsttitle
element inherits the language of the document (en
); the others have explicitly-declared languages for each element. If the user's preferred language (out of those provided) is American English, the icon title is the American spelling "Favorite". If the user's preferred language is Dutch, the icon title is "Favoriet". If the user's preference list includes generic English ranked higher than Dutch, the title is "Favourite" with British spelling. If the user does not understand either Dutch or English, the title will be the star symbol character—which is not ideal (most screen readers will read it as a localized version of "black star"), but better than no text alternative at all.
Authors should be aware that SVG 1.1-supporting user agents that have not yet implemented multi-lingual descriptive text will normally select the first element of each type, regardless of user preferences. SVG 1.1 user agents may also fail to recognize atitle
element that is not the first child of its parent, or adesc
element that has previous siblings that are not other descriptive elements.
The use of more than one‘title’ or‘desc’ element toprovide localised information is at risk, with no known implementations.
User agents must make the text content of selected 'title' and 'desc' elements available to platform accessibility APIs as part of the name and description computation for the parent element, as defined in theSVG Accessibility API Mappings [SVG-AAM] specification.
Inclusion of any 'title' or 'desc' elements as a direct child of arendered element indicates that the rendered element is of semantic importance in the graphic.Authors should not, andSVG generators must not, include empty 'title' or 'desc' elements with no text content or whitespace-only text content,as this will result in a nameless object being presented to assistive technology users.
If an individual graphic element has no meaning on its own,alternative text should instead be provided for the nearest container element that describes a meaningful object.Authors should use grouping (‘g’) elements to structure their drawing elements into meaningful objects, and name those groups with‘title’.Conversely, if a container object is used simply to apply styles or layout,and neither defines an object nor provides meaningful grouping structure,it does not need alternative text.
Descriptive text elements whose parent isnot rendered may be used by authors or authoring tools as reference information; authors are warned that this data is not normally available to end users viewing the graphic through assistive technologies. Nonetheless, anon-rendered element may be referenced as part of the accessible name or description of a rendered element (as defined inSVG-AAM), and the recursive computation will use descriptive child elements of the referenced element.
Description and title elements may contain marked-up textfrom other namespaces, using standard XML mechanisms to indicate the namespace.However, authors should not rely on such markup to provide meaning to alternative text;only the plain text content is currently required to be exposed to assistive technologies.
The HTML parser treats all markup within‘title’ and‘desc’ the same way it treats markkup in an HTML fragment; most elements will be assigned to the HTML namespace.
User agents may use markup within‘title’to influence the visual presentation of titles (such as tooltips),but are not required to do so.
The‘title’ child element represents a short text alternative for theelement.
On a link, this could be the title or a description of the target resource; on animage or drawing object, it could be a short description of thegraphic; on interactive content, it could be a label for, or instructions for, useof the element; and so forth.
Authors should not provide redundant information in a‘title’ elementif there is also a visible label for the drawing element (e.g., using a‘text’ element).Instead, the visual label should be associated with the drawing elementusing an‘aria-labelledby’ attribute.
Interactive user agents should make the plain text content of‘title’ elements available in response to user interaction, in a manner consistent with platform conventions;existing user agents commonly render‘title’ elements asa tooltip on hovering the parent element.
Authors should provide a‘title’ child element to the root svgelement within a stand-alone SVG document. Since users often consult documentsout of context, authors should provide context-rich titles. Thus, instead of atitle such as "Introduction", which doesn't provide much contextual background,authors should supply a title such as "Introduction to Medieval Bee-Keeping"instead. For reasons of accessibility, user agents should always make thecontent of the ‘title’ child element to the root svg element available tousers.However, this is typically done through other means than the tooltips used for nested SVG and graphics elements, e.g., by displaying in a browser tab.
The‘desc’ element represents more detailed textualinformation for the element such as a description. This is typically exposed to assistivetechnologies to provide more detailed information, such as a description of the visual appearance of a graphic or help to explain the functionality of a complex widget. It is not typically available to other users, so should not be used for essential instructions.
Authors may associate detailed information, including visible text, with part of the graphicusing‘aria-describedby’ attribute(on the described element or a parent container),with the value being an ID reference to one or more SVG or HTML elements containing the description.The‘aria-describedby’ attribute takes precedenceover the child‘desc’ when providing a description.If an element has both visible description and a child‘desc’ element providing supplementary information,authors should explicitly include the‘id’ of the element itself in its own‘aria-describedby’ list, in order to concatenate the two descriptions together.
Metadata which is included with SVG content should bespecified within‘metadata’elements. The contents of the‘metadata’ should be elements fromother XML namespaces, with these elements from these namespacesexpressed in a manner conforming with theNamespaces in XML Recommendation[xml-names].
SVG 2 removes the recommendation to structure metadataelements in any particular way.
Metadata content is not directly rendered;thedisplay value for the‘metadata’ elementmust always be set tononeby theuser agent style sheet,and this declaration must have importance over any other CSS rule or presentation attribute.
Here is an example of how metadata can be included in an SVGdocument. The example uses the Dublin Core version 1.1 schema.(Other XML-compatible metadata languages, including ones notbased on RDF, can be used also.)
<?xml version="1.0" standalone="yes"?><svg width="4in" height="3in" xmlns = 'http://www.w3.org/2000/svg'> <desc xmlns:myfoo="http://example.org/myfoo"> <myfoo:title>This is a financial report</myfoo:title> <myfoo:descr>The global description uses markup from the <myfoo:emph>myfoo</myfoo:emph> namespace.</myfoo:descr> <myfoo:scene><myfoo:what>widget $growth</myfoo:what> <myfoo:contains>$three $graph-bar</myfoo:contains> <myfoo:when>1998 $through 2000</myfoo:when> </myfoo:scene> </desc> <metadata> <rdf:RDF xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs = "http://www.w3.org/2000/01/rdf-schema#" xmlns:dc = "http://purl.org/dc/elements/1.1/" > <rdf:Description about="http://example.org/myfoo" dc:title="MyFoo Financial Report" dc:description="$three $bar $thousands $dollars $from 1998 $through 2000" dc:publisher="Example Organization" dc:date="2000-04-11" dc:format="image/svg+xml" dc:language="en" > <dc:creator> <rdf:Bag> <rdf:li>Irving Bird</rdf:li> <rdf:li>Mary Lambert</rdf:li> </rdf:Bag> </dc:creator> </rdf:Description> </rdf:RDF> </metadata></svg>
For user agents that support HTML, the following HTML elements (inthe HTML namespace) must be supported in SVG documents:
Note that thebase
element will affect all URL values in the document, including e.g. paint server references or‘use’ element references.However, whenprocessing URL referencesto identify a specific target element,the user agent must always compare the generated absolute URL against the current document base URLto determine whether it is asame-document URL reference.In this way, target-fragment only references to elements in the same document remain valid,regardless of any changes to the document base URL.
SVG allows inclusion of elements from foreign namespacesanywhere within the SVG content.In general, the SVG user agentmust include the unknown foreign-namespaced elements in the DOMbut will ignore and exclude them for rendering purposes.
The notable exceptions are described in theEmbedded Content chapterunderHTML elements in SVG subtreesandEmbedding Foreign ObjectTypes.Also see the handling ofunknown elementsin the SVG namespace, which are treated differently.
Additionally, SVG allows inclusion of attributes fromforeign namespaces on any SVG element.The SVG user agent mustinclude unknown attributes in the DOM but should otherwise ignoreunknown attributes.
Authors should be aware that unknown namespaced elements and attributes will not be parsed as such by the HTML parser. Instead, the namespace prefix will be included in the tag or attribute name, elements will be placed in the parent element namespace and attributes in the default namespace.
To add custom attributes in a way that will result in consistent parsing in both XML and HTML documents, authors may use the‘data-*’ attributes. These can be added to SVG‘metadata’ elements if the information they encode is not associated with any other element in the document.
SVG's ability to include foreign namespaces can be used forthe following purposes:
For example, a business graphics authoring applicationmight want to include some private data within an SVG documentso that it could properly reassemble the chart (a pie chart inthis case) upon reading it back in:
<?xml version="1.0" standalone="yes"?><svg width="4in" height="3in" xmlns = 'http://www.w3.org/2000/svg'> <defs> <myapp:piechart xmlns:myapp="http://example.org/myapp" title="Sales by Region"> <myapp:pieslice label="Northern Region" value="1.23"/> <myapp:pieslice label="Eastern Region" value="2.53"/> <myapp:pieslice label="Southern Region" value="3.89"/> <myapp:pieslice label="Western Region" value="2.04"/> <!-- Other private data goes here --> </myapp:piechart> </defs> <desc>This chart includes private data in another namespace </desc> <!-- In here would be the actual SVG graphics elements which draw the pie chart --></svg>
The‘id’ attribute is available on all SVG elements:
Name | Value | Initial value | Animatable |
---|---|---|---|
id | (see below) | (none) | no |
Must reflect theelement's ID [DOM]. The‘id’ attribute must be unique within the node tree, must not be an empty string, and must not contain any whitespace characters.
Additional requirements apply in order for the‘id’ attribute to be valid in XML documents, as defined in the specification for the relevant version of XML. A stand-alone SVG document uses XML 1.0 syntax [xml], which specifies that valid‘id’ values areXML name tokens. Valid XML 1.0 names only include designated characters (letters, digits, and a few punctuation marks), and do not start with a digit, a full stop (.) character, or a hyphen-minus (-) character.
User agents should process‘id’ values in SVG files irrespective of XML validity.
Authors should avoid the use of‘id’ values that would be parsed as anSVG view specification or abasic media fragment when used as a URL target fragment.
The‘lang’ attribute (in no namespace) specifies the primary language for the element's contents andfor any of the element's attributes that contain text.
The‘lang’ attribute in the XML namespace is defined in XML [xml].
If these attributes are omitted from an element, then the language of this element is the same as the language of its parent element, if any.
The‘lang’ attribute in the XML namespace may be used on SVG elements in XML documents.If both the‘lang’ attribute in no namespace and the‘lang’ attributein the XML namespace are specified on the same element, they must have exactly the same value when compared in an ASCII case-insensitive manner.
If both the‘lang’ attribute in no namespace and the‘lang’ attribute in theXML namespace are set on an element, user agents must use the‘lang’ attribute in the XML namespace, andthe‘lang’ attribute in no namespace must be ignored for the purposes of determining the element's language.
Name | Value | Initial value | Animatable |
---|---|---|---|
lang | Language-Tag[ABNF] | (none) | no |
The‘lang’ attribute specifies the primary language for the element's contents andfor any of the element's attributes that contain text. Its value must be a valid BCP 47 language tag,or the empty string. Setting the attribute to the empty string indicates that the primary language is unknown.[BCP47].
SVG 2 Requirement: | Deprecate the use of‘xml:space’ to affect text layout and use the ‘white-space’ property instead. |
---|---|
Resolution: | We drop xml:space from SVG 2 and remove the relating tests from the SVG 1.1. test suite. |
Purpose: | To align with CSS. |
Owner: | Chris (ACTION-3004, done; andACTION-3005, done) |
Status | Done. |
Name | Value | Initial value | Animatable |
---|---|---|---|
xml:space | (see below) | default | no |
Deprecated XML attribute to specify whether white space is preserved in character data. The only possible values are the strings'default' and'preserve', without white space. Refer to theExtensible Markup Language (XML) 1.0 Recommendation [xml] and to the discussionwhite space handling in SVG.
New content should use thewhite-space property instead.
Name | Value | Initial value | Animatable |
---|---|---|---|
tabindex | valid integer[HTML] | (none) | no |
This content attribute allows authors to control whether an element is focusable, whether it is supposed to be reachable usingsequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation.
The name "tab index" comes from the common use of the "tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward through the focusable elements that can be reached using sequential focus navigation.
All SVG elements supportcustom data attributes,which are those in no namespace whose names begin with the string "data-".See therequirementsfor custom data attributes in the HTML specification.
Note that the above list of ARIA attributes may be expanded by future WAI-ARIA specifications.
Anyrenderable element may have an ARIA role attribute specified; the role attribute is ignored onnon-rendered elements.The attribute, if specified, must have a value that is aset of space-separated tokens representing the various WAI-ARIA roles that the element belongs to.These tokens are role values defined inDefinition of Roles([wai-aria], section 5.4) andGraphics Roles([graphics-aria-1.0], section 4).
The WAI-ARIA role that an SVG element has assigned to it is the first validrole found in the list of tokens generated when the role attributeis split on spaces.A valid role is a recognized, non-abstract role that isallowed for the element type.
Name | Value | Initial value | Animatable |
---|---|---|---|
role | set of space-separated tokens[HTML] | (see below) | no |
The‘role’ attribute must be aset of space-separated tokens having values defined inDefinition of Roles ([wai-aria], section 5.4).
The role value is a set of white-space separated machine-extractable semantic information used to define the purpose of the element.
Theinitial value for the‘role’ attribute, for each SVG element, is the correspondingdefault implied ARIA semantic for SVG elements.
To be valid and useful, many element roles require additional information to be providedin the form of an accessible nameor explicitstate and property values.Accessible names may be provided using SVGdescriptive elements orARIA attributes.The requirements for each role are indicated where the role is defined, e.g., inWAI-ARIA([WAI-ARIA]) or theWAI-ARIA Graphics Module([graphics-aria-1.0]).
WAI-ARIA state and property attributes may be specified on SVG elements.These attributes are defined by ARIA inDefinitions of States and Properties (all aria-* attributes)([wai-aria], section 6.6).
These attributes, if specified, must have a value that is the WAI-ARIA valuetype in the "Value" field of the definition for the state or property, mapped tothe appropriate SVG value type according toMapping WAI-ARIA Value types to languagesusing the SVG mapping ([wai-aria], section 10.2).
The attributes are animatable; if animation is used to change the state of the graphic, or to change its content in a way that alters the correct alternative text description, the same method of animation should be used to update the corresponding ARIA state or property attribute.
WAI-ARIA State and Property attributes can be used on any element. They arenot always meaningful, however, and in such cases user agents might not performany processing aside from including them in the DOM. State and property attributes areprocessed according to theARIA andSVG Accessibility API Mappings specificationspecifications. [wai-aria] [svg-aam-1.0]
The following table defines thedefault implicit ARIA semantics that apply toSVG elements. Each language feature (element) in a cell in the first column implies the ARIA semantics (role, states, and/or properties) given in the cell in the second column of the same row. The third column defines restrictions as to what WAI-ARIA semantic (role, state, or property) may or may not apply.
For many graphics elements, an implicit role is only assigned if the author provides information that indicates semantic importance. The completeinclusion criteria for the accessibility tree are defined by theSVG Accessibility API Mappings specification for user agents [svg-aam-1.0]. For authors, the preferred means of indicating semantic importance is to provide an accessible name for the element. This can be done through a direct child‘title’ element, or through the‘aria-label’ or‘aria-labelledby’ attributes. Authors should use one of these methods to provide an accessible name for any content that is essential to the comprehension of the SVG, and especially for any interactive content.
Language feature | Default implied ARIA semantics | Allowed roles |
---|---|---|
‘a’ | link role if the element has a validhref orxlink:href attribute. Fora elements that are not links, the default semantics are the same astspan if thea element is a descendent oftext , or the same asg otherwise. | no restrictions |
‘audio’ | platform-specific role mappings, as defined in theHTML Accessibility API Mappings specification | If specified, role must beapplication |
‘canvas’ | platform-specific role mappings, as defined in theHTML Accessibility API Mappings specification | no restrictions |
‘circle’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘clipPath’ | none | no role may be applied |
‘defs’ | none | no role may be applied |
‘desc’ | none | no role may be applied |
‘ellipse’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘feBlend’ | none | no role may be applied |
‘feColorMatrix’ | none | no role may be applied |
‘feComponentTransfer’ | none | no role may be applied |
‘feComposite’ | none | no role may be applied |
‘feConvolveMatrix’ | none | no role may be applied |
‘feDiffuseLighting’ | none | no role may be applied |
‘feDisplacementMap’ | none | no role may be applied |
‘feDistantLight’ | none | no role may be applied |
‘feDropShadow’ | none | no role may be applied |
‘feFlood’ | none | no role may be applied |
‘feFuncA’ | none | no role may be applied |
‘feFuncB’ | none | no role may be applied |
‘feFuncG’ | none | no role may be applied |
‘feFuncR’ | none | no role may be applied |
‘feGaussianBlur’ | none | no role may be applied |
‘feImage’ | none | no role may be applied |
‘feMerge’ | none | no role may be applied |
‘feMergeNode’ | none | no role may be applied |
‘feMorphology’ | none | no role may be applied |
‘feOffset’ | none | no role may be applied |
‘fePointLight’ | none | no role may be applied |
‘feSpecularLighting’ | none | no role may be applied |
‘feSpotLight’ | none | no role may be applied |
‘feTile’ | none | no role may be applied |
‘feTurbulence’ | none | no role may be applied |
‘filter’ | none | no role may be applied |
‘foreignObject’ | group role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘g’ | group role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘iframe’ | platform-specific role mappings, as defined in theHTML Accessibility API Mappings specification | If Specified, role must be eitherapplication ,document , orimg roles |
‘image’ | img role | no restrictions |
‘line’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘linearGradient’ | none | no role may be applied |
‘marker’ | none | no role may be applied |
‘mask’ | none | no role may be applied |
‘metadata’ | none | no role may be applied |
‘mpath’ | none | no role may be applied |
‘path’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘pattern’ | none | no role may be applied |
‘polygon’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘polyline’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘radialGradient’ | none | no role may be applied |
‘rect’ | graphics-symbol role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘script’ | none | no role may be applied |
‘stop’ | none | no role may be applied |
‘style’ | none | no role may be applied |
‘svg’ | graphics-document role | no restrictions |
‘switch’ | none | no role may be applied |
‘symbol’ | graphics-object role if the element is a renderedelement instance that meets theinclusion criteria, otherwisenone | no restrictions |
‘text’ | group role, with platform-specific role mappings, as defined in theSVG Accessibility API Mappings specification | no restrictions |
‘textPath’ | group role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘title’ | none | no role may be applied |
‘tspan’ | group role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘use’ | graphics-object role if the element meets theinclusion criteria, otherwisenone | no restrictions |
‘video’ | platform-specific role mappings, as defined in theHTML Accessibility API Mappings specification | If specified, role must beapplication |
‘view’ | none | no role may be applied |
The DOM Core specification defines aDocument interface, which this specification extends.
In the case where an SVG document is embedded by reference,such as when an HTML document has an‘object’element whose‘data’ attribute references an SVGdocument (i.e., a document whose MIME type is "image/svg+xml"and whose root element is thus an‘svg’ element), there will existtwo distinct DOM hierarchies. The first DOM hierarchy will be for thereferencing document (e.g., an XHTML document). The second DOM hierarchywill be for the referenced SVG document.
partial interfaceDocument { readonly attributeSVGSVGElement?rootElement;};
TherootElement IDL attributerepresents the root‘svg’ element. On gettingrootElement, the root elementof the document is returned, if it is an‘svg’ element, or nullotherwise.
This attribute is deprecated, and may be removed in a future SVG specification.Authors are encouraged to use thedocumentElement attribute onDocument instead.
SVG implementations that implement HTML must support theHTML extensions to the document interface.Other SVG implementations must support the following IDL fragment.
// must only be implemented in certain implementationspartial interfaceDocument { readonly attribute DOMString title; readonly attribute DOMString referrer; readonly attribute DOMString domain; readonly attribute Element?activeElement;};
The title, referrer, domain andactiveElement IDL attributes must behave the same asthe corresponding IDL attributes defined in HTML.
AnSVGSVGElement object represents an‘svg’ elementin the DOM. TheSVGSVGElement interface also containsmiscellaneous utility methods, such as data type object factory methods.
AnSVGSVGElement object maintains an internalDOMPoint object, called itscurrent translate point object,which is the object returned from thecurrentTranslateIDL attribute.
[Exposed=Window]interfaceSVGSVGElement :SVGGraphicsElement { [SameObject] readonly attributeSVGAnimatedLengthx; [SameObject] readonly attributeSVGAnimatedLengthy; [SameObject] readonly attributeSVGAnimatedLengthwidth; [SameObject] readonly attributeSVGAnimatedLengthheight; attribute floatcurrentScale; [SameObject] readonly attributeDOMPointReadOnlycurrentTranslate;NodeListgetIntersectionList(DOMRectReadOnly rect,SVGElement? referenceElement);NodeListgetEnclosureList(DOMRectReadOnly rect,SVGElement? referenceElement); booleancheckIntersection(SVGElement element,DOMRectReadOnly rect); booleancheckEnclosure(SVGElement element,DOMRectReadOnly rect); voiddeselectAll();SVGNumbercreateSVGNumber();SVGLengthcreateSVGLength();SVGAnglecreateSVGAngle();DOMPointcreateSVGPoint();DOMMatrixcreateSVGMatrix();DOMRectcreateSVGRect();SVGTransformcreateSVGTransform();SVGTransformcreateSVGTransformFromMatrix(DOMMatrixReadOnly matrix);ElementgetElementById(DOMString elementId);// Deprecated methods that have no effect when called,// but which are kept for compatibility reasons. unsigned longsuspendRedraw(unsigned long maxWaitMilliseconds); voidunsuspendRedraw(unsigned long suspendHandleID); voidunsuspendRedrawAll(); voidforceRedraw();};SVGSVGElement includesSVGFitToViewBox;SVGSVGElement includesSVGZoomAndPan;SVGSVGElement includesWindowEventHandlers;
Thex,y,width andheight IDL attributesreflect the computed values of thex,y,width andheight properties and their correspondingpresentation attributes, respectively.
ThecurrentScale andcurrentTranslate IDLattributes represent the transform applied to the document inresponse to user magnification and panning operations, as described underMagnification and panning.
The document's magnification and panningtransform is a 2x3 matrix of the form[currentScale 0 0 currentScale currentTranslate.x currentTranslate.y].The value of the‘transform’ property does not affectcurrentScale orcurrentTranslate.
On gettingcurrentScale,the following steps are run:
On settingcurrentScale,the following steps are run:
On gettingcurrentTranslate,theSVGSVGElement object'scurrenttranslate point object is returned. This objectrepresents the current translationfor the‘svg’ element. Acurrenttranslate point object must beread onlywhen its‘svg’ element is not theoutermost svg element,and writable otherwise.
See the rules forassigning to a DOMPointfor how modifying thecurrenttranslate point object affects the document's magnification and panning transform.
Whenever the document's magnification and panning transform changesin response to user interaction or whenever theoutermost svg elementchanges, the following steps are run:
Running these steps when theoutermost svg elementchanges will ensure that if the document element is replaced with a different‘svg’ element, that itscurrentTranslatewill be immediately updated to reflect the translation component ofthe document's magnification and panning transform.
Whenever an‘svg’ element is no longeroutermost svg element,the x and y components of itscurrenttranslate point object must be set to 0.
Note that the value of the‘zoomAndPan’ attributeon theoutermost svg element only controls whether the document'smagnification and panning transform can be updated through user interaction.Regardless of the value of that attribute, the current scale and translationcan be changed by modifyingcurrentScaleandcurrentTranslate.
ThesuspendRedraw,unsuspendRedraw,unsuspendRedrawAllandforceRedrawmethods are all deprecated and defined to have no effect. Whenthe suspendRedraw method is called, it must return 1.
ThegetIntersectionList,getEnclosureList,checkIntersection andcheckEnclosure methods areused to perform geometry operations ongraphics elements to findthose whose (or check whether their) graphical content lies partially orcompletely within a given rectangle.
Tofind the intersectingor enclosed descendants of a given elementelementwith a given rectanglerectangle usingancestoras the element in whose coordinate spacerectangle isto be interpreted, the following steps are run:
This means that although we look at the elements in theuse-element shadow tree, we don't place theelement instances or theircorresponding element in theresult list; only the‘use’ element itself is returned.
Tofind the non-containergraphics elements within a given elementelement, the followingsteps are run:
When getIntersectionList(rect,referenceElement) orgetEnclosureList(rect,referenceElement) is called,the following steps are run:
When checkIntersection(element,rect) orcheckEnclosure(element,rect) is called,the following steps are run:
ThedeselectAll method isused to remove any selections from the document. When deselectAll() is called,allrangesfrom the document'sselectionare removed and theselection'sdirection is set toforwards. [DOM][EDITING]This method is deprecated, as it duplicates functionality from the Selection API.
This is equivalent to callingdocument.getSelection().removeAllRanges()
on the document that this‘svg’ element is in.
ThecreateSVGNumber,createSVGLength,createSVGAngle,createSVGPoint,createSVGMatrix,createSVGRect andcreateSVGTransformmethods are all factory functions used to create a new datatype objectof a particular type. When one of these methods is called, a newobject is returned according to the following table:
Method | Object and details |
---|---|
createSVGNumber | A new,detachedSVGNumber object whose value is 0. |
createSVGLength | A new,detachedSVGLength object whose value is the unitless<number> 0. |
createSVGAngle | A new,detachedSVGAngle object whose value is the unitless<number> 0. |
createSVGPoint | A new,detachedDOMPoint object whose coordinates are all 0. |
createSVGMatrix | A new,detachedDOMMatrix object representing the identity matrix. |
createSVGRect | A new,DOMRect object whose x, y, width and height are all 0. |
createSVGTransform | A new,detachedSVGTransform object whose value ismatrix(1, 0, 0, 1, 0, 0). |
ThecreateSVGPoint,createSVGMatrix andcreateSVGRect methodsare all deprecated and kept only for compatibility with legacy content.Authors are encouraged to use theDOMPoint,DOMMatrix andDOMRect constructors instead.
ThecreateSVGTransformFromMatrixmethod is used to create a newSVGTransform object from a matrix object.Its behavior is the same as thecreateSVGTransformFromMatrixmethod onSVGTransformList.
ThegetElementById method,must return the first element intree order, within the‘svg’ element's descendants, whose ID iselementId, ornull if there is no such element.
AnSVGGElement object represents a‘g’ element in the DOM.
[Exposed=Window]interfaceSVGGElement :SVGGraphicsElement {};
AnSVGUnknownElement object represents an unknown element in the SVG namespace.
[Exposed=Window]interfaceSVGUnknownElement :SVGGraphicsElement {};
AnSVGDefsElement object represents a‘defs’ element in the DOM.
[Exposed=Window]interfaceSVGDefsElement :SVGGraphicsElement {};
AnSVGDescElement object represents a‘desc’ element in the DOM.
[Exposed=Window]interfaceSVGDescElement :SVGElement {};
AnSVGMetadataElement object represents a‘metadata’ element in the DOM.
[Exposed=Window]interfaceSVGMetadataElement :SVGElement {};
AnSVGTitleElement object represents a‘title’ element in the DOM.
[Exposed=Window]interfaceSVGTitleElement :SVGElement {};
AnSVGSymbolElement object represents a‘symbol’ element in the DOM.
[Exposed=Window]interfaceSVGSymbolElement :SVGGraphicsElement {};SVGSymbolElement includesSVGFitToViewBox;
New in SVG 2. TheSVGSymbolElement interface now inherits fromSVGGraphicsElement, so that the instantiated symbol in the shadow DOM can be queried as a graphics element.
AnSVGUseElement object represents a‘use’ element in the DOM.
[Exposed=Window]interfaceSVGUseElement :SVGGraphicsElement { [SameObject] readonly attributeSVGAnimatedLengthx; [SameObject] readonly attributeSVGAnimatedLengthy; [SameObject] readonly attributeSVGAnimatedLengthwidth; [SameObject] readonly attributeSVGAnimatedLengthheight; [SameObject] readonly attributeSVGElement?instanceRoot; [SameObject] readonly attributeSVGElement?animatedInstanceRoot;};SVGUseElement includesSVGURIReference;
Thex,y,width andheight IDL attributesreflect the computed values of thex,y,width andheight properties and their correspondingpresentation attributes, respectively.
TheinstanceRoot andanimatedInstanceRootIDL attributes both point to theinstance root,theSVGElementInstance that is a direct childof this element's shadow root(u.instanceRoot
is equivalent to gettingu.shadowRoot.firstChild
).If this element does not have a shadow tree(for example, because its URI is invalidor because it has been disabled byconditional processing),then getting these attributes returns null.
The root object of eachuse-element shadow tree implements theSVGUseElementShadowRoot interface. This interface does not currently define any extensions to the properties and methods defined for theShadowRoot interface andDocumentOrShadowRoot mixin. However, the tree rooted at this node is entirely read-only from the perspective of author scripts.
[Exposed=Window]interfaceSVGUseElementShadowRoot :ShadowRoot {};
TheSVGElementInstance interface defines extensions to theSVGElement interface, which are only used for elements in ause-element shadow tree.
In previous versions of SVG, SVG element instances were defined as non-element objects that were valid event targets but not full DOM nodes. This specification re-defines theuse-element shadow tree to be consistent with the Shadow DOM specification, which means that instances are actual SVGElement objects. This interface adds the missing functionality for backwards compatibility. However, authors should be aware that compatibility is not perfect, and design their scripts accordingly. Also note that these properties will not be available on HTML-namespaced element objects in the shadow tree.
interface mixinSVGElementInstance { [SameObject] readonly attributeSVGElement?correspondingElement; [SameObject] readonly attributeSVGUseElement?correspondingUseElement;};
ThecorrespondingElement IDL attributepoints to thecorresponding element if this element is anelement instance in ause-element shadow tree,or is null otherwise.
When thereferenced element is in an external file, the presence of this pointer implies that the entire DOM of the external file must be maintained in memory. However, as currently specified, the external DOM is read-only. It therefore offers limited functionality and a potentially large performance impact. Pending feedback from implementers, authors should consider the use ofcorrespondingElement
with external file references to be at-risk.
ThecorrespondingUseElement IDL attributepoints to thecorresponding use element if this element is anelement instance in ause-element shadow tree,or is null otherwise.
TheShadowAnimation inteface defines a read-onlyAnimation object, which mirrors all changes to thesourceAnimation object from which it was constructed. They are used to mirror author-initiated animation objects in theuse-element shadow tree.
[Constructor(Animation source,Animatable newTarget), Exposed=Window]interfaceShadowAnimation :Animation { [SameObject] readonly attributeAnimationsourceAnimation;};
ThesourceAnimation IDL property points to theAnimation object passed in the constructor.
The constructor generates a newShadowAnimation object, which reflects all properties on thesourceAnimation, except that itseffect
is created by constructing a newKeyframeEffectReadOnly
using the keyframe effect of thesourceAnimation as its source, and then modifying itstarget
to match thenewTarget
parameter.
AShadowAnimation is read-only. Any attempt to set any of the inherited IDL properties, or call any of theAnimation methods that change its state, must throw aNoModificationAllowedError
. However, the user agent must ensure that any changes to the properties or state of thesourceAnimation are reflected in changes to theShadowAnimation.
AnSVGSwitchElement object represents a‘switch’ element in the DOM.
[Exposed=Window]interfaceSVGSwitchElement :SVGGraphicsElement {};
This interface provides access to an SVG document embedded by referencein another DOM-based language. The expectation is that the interface isimplemented on DOM objects that allow such SVG document references.
This interface is deprecated and may be dropped from future versions ofthe SVG specification. To access the SVG document inside an‘iframe’ or‘object’ element,authors are suggested to use thecontentDocument
attribute on theHTMLIFrameElement orHTMLObjectElementinterface, respectively.
TheHTMLIFrameElement,HTMLEmbedElementandHTMLObjectElement interfaces all define their own getSVGDocumentmethod, which provides access to the SVG document in the same way thattheGetSVGDocument does. Those three interfaces therefore do not needto implementGetSVGDocument. Still, authors are strongly recommendedto use contentDocument instead.
interface mixinGetSVGDocument {DocumentgetSVGDocument();};
ThegetSVGDocument methodis used to return a referenced SVG document. When getSVGDocument() is called,it must return theDocument object referenced by the embedding elementthat implements theGetSVGDocument interface; if there is no document,null is returned.
Note that this does no check to see whether the referenceddocument is indeed an SVG document. Instead, any document is returned.