Using SVG with CSS3 and HTML5 — Supplementary Material

Example code and online extras for the O'Reilly Media book by Amelia Bellamy-Royds, Kurt Cagle, and Dudley Storey.

SVG Elements and Attributes

This reference lists all the elements we’ve introduced, and their attributes. A few element-specific presentation attributes are included, but the full reference for presentation attributes is the SVG Style Properties list.

It starts with sections on shared attributes, then elements are grouped by category, loosely following the order from the book. The final section lists deprecated an unsupported elements.

Common Attributes for All SVG Elements#

Some attributes in SVG can be added to any element—​although they won’t always have an effect.

id#

A unique identifier for distinguishing this element from all other elements in the document. Used in SVG element cross-references, link targets, the JavaScript getElementById() methods, CSS selectors, ARIA relationship attributes, and more. Some SVG elements will have no effect without an id.

  • Value must be a non-empty string that does not contain any whitespace.

  • The ID should be completely unique within a document.

  • For XML compatibility, the ID should start with a letter; non-ASCII letters are allowed, but may not be supported everywhere.

  • For XML compatibility, the ID should contain only letters, numbers, periods (.), and hyphens (-).

class#

A set of identifiers that describe custom features of this element, which it might share with other elements. Used in CSS selectors and the JavaScript getElementsByClassName() method, among others.

  • Value is a list of whitespace-separated tokens (the individual classes).

  • The tokens themselves can be any non-whitespace characters (letters, numbers, symbols, emojis), but it’s best to avoid symbols that need to be escaped in CSS; this includes numbers as the first character of a class name.

style#

A list of CSS style declarations that should apply to this element.

  • Format is a list of property-name: property-value; pairs.

  • The final ; in a list is optional.

  • Whitespace is optional before and after property names and values.

  • The property value can be followed by !important, but that is really not recommended in inline styles.

  • Inline styles already have higher specificity than other styles on the same element (see Chapter 3 in the book for details).

Presentation attributes#

All elements in SVG can have presentation attributes. Although some attributes won’t have a noticeable effect on certain elements, they can still affect the inherited style values. Presentation attributes have lower specificity than other styles on the same element (see Chapter 3 in the book for details).

See the Style Properties Reference for a list of all style properties applicable to SVG, including which ones are available as presentation attributes.

transform #

Transformations to apply to this element (and therefore its children).

  • A list of transformation functions, as defined in the Transform Functions Reference.

  • Default is no transformation.

  • In SVG 1, only valid on <g>, <a>, shape elements, and <text>. Ignored on inline text-formatting elements (<tspan>, <textPath>, and <a> within text).

  • Converted to a presentation attribute in SVG 2/CSS3, but with additional legacy syntax compared to the transform property. The attribute is extended to apply to <svg> and <symbol> elements and the new paint server elements (older paint servers use the legacy patternTransform or gradientTransform attributes).

xml:lang (or lang in SVG 2)#

The human-readable language of text content for this element and child elements (unless the child element has a different lang attribute). Use it for visible text, but also for <title> and other alternative text. Otherwise, screen readers can mangle your descriptions by trying to pronounce them in the wrong language!

  • The xml:lang version is recommended for backwards compatibility.

  • You do not need to declare a namespace for the xml prefix.

  • Value is a IETF language tag: two lowercase letters for the language (en for English, de for German, jp for Japanese), optionally followed by a hyphen and additional tags for the country code (en-US for American English, pt-BR for Brazillian Portuguese), language variant, or script.

  • An attribute with an empty string means unknown language, no language, or any language (e.g., emojis or numerical data).

  • The :lang(code) selector in CSS will select elements with a specified language, regardless of whether they have the attribute directly or inherit the language of their parent.

xml:space#

SVG 1 attribute that was supposed to control whether whitespace in the markup gets collapsed for text rendering. Not supported in all browsers; SVG 2 replaces with the CSS white-space property.

xmlns and xmlns:prefix#

Define XML namespace URIs to be used when parsing this element and its child elements. At least an xmlns is required on the root <svg> element in standalone SVG. Ignored by the HTML parser.

For content that works with both the XML and HTML parser, use xmlns (to set the default namespace) instead of prefixes, except for xlink attributes:

  • Declare the SVG namespace on the top-level <svg> element, with xmlns="http://www.w3.org/2000/svg".

  • For HTML content inside of SVG (e.g., in a <foreignObject>), declare the HTML namespace on the top-level HTML container element: xmlns="http://www.w3.org/1999/xhtml".

  • If you use any xlink attributes, declare the xlink prefix on the top-level <svg> element: xmlns:xlink="http://www.w3.org/1999/xlink".

  • You don’t need to declare an xml prefix in markup (e.g., for xml:lang), but if you’re creating that attribute with the setAttributeNS() DOM method, the namespace is "http://www.w3.org/XML/1998/namespace".

tabindex#

The keyboard focus priority level. Works the same as the equivalent attribute in HTML (MDN).

  • Value is any integer, but only 0 and -1 are recommended.

  • 0 means add to the normal tab order.

  • -1 means make the element focusable by scripts, but not part of the normal tab order. Use it for custom scripted widgets that you want to focus with arrow keys, or for elements that are temporarily disabled.

  • A positive integer value adds the element to a higher-priority tab index, which gets tab focus before any other elements in the page.

  • Only applies to graphics elements (shapes, text, images, etc.) or containers for graphics elements (groups, <svg>); avoid using on pre-defined graphics (e.g., inside a <symbol>) that aren’t drawn directly.

  • New in SVG 2. Supported in all major browser versions released since mid-2016.

role and ARIA attributes#

Descriptions of the function of the element, to be used by assistive technologies (such as screen readers or voice-control systems). The attributes are used in the same way as ARIA for HTML. These attributes do not change the actual function of the element, only how it is communicated; the web author is required to add any scripted behavior that is required to match the role. See the Using ARIA guide for more details.

Browser support for ARIA in SVG is imperfect, but getting better.

Custom data attributes#

Any additional data added by the author (or by the authoring software). Two formats are acceptable:

  • In XML/standalone SVG, create a custom XML namespace for your attributes. The namespace URL can be any URL that you own, the prefix can be anything unique for the document, and the attributes can any XML-compatible attribute names and values. If you use an XML validator, you may get warnings, but nothing should break.

  • For SVG-in-HTML, use HTML-style data attributes; any attribute name that starts with data- is for custom data. Beware: the matching dataset DOM property on the element object is new in SVG 2, and won’t be supported everywhere. Use getAttribute()/setAttribute() for best support.

systemLanguage#

Indicates for which languages this content should be included. If the user’s browser is not set to accept the specified language, this element (and its children) will not be drawn. Usually used on a child of a <switch> element, to swap between different language versions.

  • Value is a comma-separated list of IETF language tags; if any of the languages match the user’s list of accepted languages, then the element can be shown.

  • However, at most one child of a <switch> block will ever be shown; SVG 2 says to pick the best language match for the user’s preferences, but most browsers still follow SVG 1.1, and pick the first match.

requiredFeatures and requiredExtensions#

Provides lists of SVG features which must be supported by the browser (or other software) in order for this element (and its children) to be drawn. Usually used on a child of a <switch> element, to provide fallback options if the required features aren’t available.

Neither attribute was very well-defined in the original SVG specs.

requiredFeatures is supposed to test for support of core SVG features:

  • Value is a whitespace-separated list of strings/URLs as defined in an appendix to the SVG 1.1 specs.

  • All items in the list must be supported, or else this element won’t be drawn. However, "support" is defined vaguely and features might still be buggy or incomplete. Some browsers will act as if they support any unrecognized strings that weren’t included in the SVG 1.1 specs.

  • The attribute has been dropped from SVG 2, and no new feature strings are expected to be added.

requiredExtensions tests for support of features defined outside the SVG specs:

  • Value is a space-separated list of URLs representing the extensions, as defined by the creators of each extension.

  • All items in the list must be supported, or else this element won’t be drawn.

  • Adobe uses this attribute (within <switch>) to insert custom binary (base64) content in an SVG file, with a switch to a fallback image.

  • Firefox accepts the XML namespace URLs for HTML and MathML as recognized "extensions", but that isn’t defined anywhere.

Repeated Attributes Used on Multiple Elements#

The attributes xlink:href, crossorigin, viewBox, preserveAspectRatio, x, y, width, and height are used on many different element types. Unique behavior will be listed for each element; this list summarizes the common features.

A URL cross-reference.

  • Value is a URL. Depending on the element, the URL could be:

    • global (another website),

    • local or relative (another file on the same web domain),

    • a target fragment reference to another element in this document (indicated by a # character followed by that element’s id value),

    • another type of fragment reference, such as an SVG view fragment.

  • In some use cases, references to external files—​and especially, to cross-origin files—​are limited by the specifications or by browser support.

  • In XML documents (including SVG), the xlink prefix must be attached to the XLink namespace, http://www.w3.org/1999/xlink, using an xmlns:xlink attribute (usually on the root <svg> element).

  • In SVG 2, the simple href attribute can be used (and over-rides an xlink:href attribute on the same element).

crossorigin#

New in SVG 2, based on the same attribute in HTML. Indicates whether the browser should request cross-origin permissions for a linked file from another web domain.

  • If specified, the value should be:

    • anonymous (request the file without using any browser cookies),

    • use-credentials (request using browser cookies).

  • An attribute with no value (or an empty string) is equivalent to anonymous.

  • The presence of the attribute implies a request to the server for cross-origin access.

  • Default (if not specified) is to not request cross-origin permissions.

viewBox#

The dimensions and offsets of a coordinate system rectangle that will be used when scaling and positioning child content of this element.

  • Four numbers, separated by whitespace or commas, describe the rectangle:

    • minimum x coordinate,

    • minimum y coordinate,

    • width,

    • height.

  • Values represent user units in the scaled coordinate system for child elements.

  • Negative values for width and height are an error.

  • Zero values for width and height disable drawing of the content.

preserveAspectRatio#

The scaling and alignment strategy that should be used when the intrinsic aspect ratio of this element (e.g., as defined by the viewBox) does not match the aspect ratio of its dimensions (defined by width and height).

  • The value may be either:

    • none,

    • an alignment keyword of the form xAlignYAlign (note the capitalization), where Align is either Min, Mid or Max,

    • an aligment keyword followed by either the meet or slice keyword.

  • The defer keyword may optionally be specified at the beginning of the value, but has no effect on an <svg> element.

  • Keywords are separated by whitespace.

  • Default xMidYMid meet; if alignment is specified without meet or slice, the default is meet.

x#

For elements that are sized to fit a layout rectangle, the horizontal position of the corner with minimum coordinates.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default is usually 0.

  • SVG 2 makes it a geometry property.

y#

For elements that are sized to fit a layout rectangle, the vertical position of the corner with minimum coordinates.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default is usually 0.

  • SVG 2 makes it a geometry property.

width#

The width of the layout rectangle.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default is usually 0, which usually disables rendering of the element.

  • Negative values are an error.

  • SVG 2 makes it a geometry property (with the default auto, with element-specific behavior).

height#

The height of the layout rectangle.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default is usually 0, which usually disables rendering of the element.

  • Negative values are an error.

  • SVG 2 makes it a geometry property (with the default auto, with element-specific behavior).

Shape Elements#

There are 7 shape elements in SVG: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect>.

For <path>, <polygon>, and <polyline>, the determination of whether an area is inside or outside the shape is affected by the fill-rule style property (or clip-rule withing clipping paths). The default behavior is nonzero; an evenodd value treats all edges as boundaries between the inside and outside of the shape.

<circle> #

A circle defined by the position of the center-point and the radius.

Strokes start at 3 o’clock and go clockwise (that is, from where the circle crosses the cx value at a y value greater than cy).

cx#

The horizontal position of the center-point

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 0.

  • SVG 2 makes it a geometry property.

cy#

The vertical position of the center-point

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 0.

  • SVG 2 makes it a geometry property.

r #

The radius of the circle.

  • A length (in user coordinates or with units) or percentage (proportional to the coordinate system diagonal length, as defined in the Units guide).

  • Default 0, which disables rendering of the circle.

  • Negative values are an error.

  • SVG 2 makes it a geometry property.

<ellipse> #

An ellipse defined by the position of the center-point and the radius in each direction.

Strokes start at 3 o’clock and go clockwise (that is, from where the ellipse crosses the cx value at a y value greater than cy).

cx#

The horizontal position of the center-point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 0.

  • SVG 2 makes it a geometry property.

cy#

The vertical position of the center-point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 0.

  • SVG 2 makes it a geometry property.

rx#

The horizontal radius of the ellipse.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 0, which disables rendering of the ellipse.

  • Negative values are an error.

  • SVG 2 makes it a geometry property (with the default auto, which behaves like the SVG 1 default for rectangles).

ry#

The vertical radius of the ellipse.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 0, which disables rendering of the ellipse.

  • Negative values are an error.

  • SVG 2 makes it a geometry property (with the default auto, which behaves like the SVG 1 default for rectangles).

<line> #

A line defined by its start and end points. Must be stroked to be visible.

Strokes start at (x1,y1).

x1#

The horizontal position of start point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 0.

y1#

The vertical position of start point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 0.

x2#

The horizontal position of end point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 0.

y2#

The vertical position of end point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 0.

<path> #

An arbitrary shape built from line and curve segments, possibly including disjoint or cut-out regions or criss-crossing edges.

Strokes follow the order of the path data. Most browsers restart stroke dash patterns for each sub-path, although that isn’t defined anywhere.

d#

The directions or data that describe the shape of the path.

  • Uses the code described in the Path Commands Reference.

  • If there are any errors, the path will be drawn up until the last path segment that the browser can correctly interpret.

  • Default is an empty string, which disables rendering of the path.

  • SVG 2 makes it a geometry property (with the default none).

<polygon> #

An arbitrary straight-line closed shape, possibly including criss-crossing edges.

Strokes follow the order of points.

points#

The list of vertices (corner-points) of the polygon.

  • Each point is defined by two numbers, representing the x and y positions of the point in user coordinates.

  • Coordinates may be separated by any mix of whitespace and commas.

  • An odd number of coordinate values is technically an error (but the browser just draws the shape up to the last complete point).

  • Default is an empty list, which disables rendering of the polygon.

<polyline> #

An arbitrary straight-line shape without a closing final stroke; when filled it is equivalent to a polygon with the same points.

Strokes follow the order of points.

points#

The list of vertices (corner-points) of the polyline; details are the same as for <polygon>.

<rect> #

A rectangle or rounded rectangle, defined by its width and height, optional corner radius, and the position of the minimum-coordinate (top-left) corner.

Strokes start at the minimum (x,y) corner and go clockwise, but if there is corner rounding, the stroke starts after the end of the curve for that corner.

x, y, width, and height#

Define the main rectangle dimensions.

  • See the definitions in the "Repeated Attributes" section.

  • An auto value of width or height (in SVG 2) is treated as 0 (matching the SVG 1 default), and disables rendering of the rectangle.

rx#

The horizontal radius of the rounding on each corner.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • A value of 0 disables corner rounding.

  • Default is to match the computed value of ry.

  • maximum value is 50% of the computed value of width.

  • Negative values are an error.

  • SVG 2 makes it a geometry property (with the default auto, which behaves like the SVG 1 default).

ry#

The vertical radius of the rounding on each corner.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • A value of 0 disables corner rounding.

  • Default is to match the computed value of rx; if rx is also unspecified, there is no corner rounding.

  • maximum value is 50% of the computed value of height.

  • Negative values are an error.

  • SVG 2 makes it a geometry property (with the default auto, which behaves like the SVG 1 default).

<mesh>#

New in SVG 2. A shape defined by the outside bounds of a linked <meshgradient>, and filled with that gradient.

Text Elements#

There are three text container elements in SVG: <text>, <tspan>, and <textPath>. However, both <tspan> and <textPath> must always be used inside a <text> element.

<text> #

A self-contained sequence of text content to be included in the graphic, possibly including child elements with separately styled or positioned text.

x#

The horizontal position of the anchor point or points.

  • A list of space- or comma-separated lengths (with units or as numbers of user units) or percentages (of the coordinate system width).

  • Values are assigned to individual characters in the text content of this or child elements.

  • Default is a single value 0.

y#

The vertical position of the anchor point or points.

  • A list of space- or comma-separated lengths (with units or as numbers of user units) or percentages (of the coordinate system width).

  • Values are assigned to individual characters in the text content of this or child elements.

  • Default is a single value 0.

dx#

The horizontal offsets to be applied to each character’s position.

  • A list of space- or comma-separated lengths (with units or as numbers of user units) or percentages (of the coordinate system width).

  • Values are assigned to individual characters in the text content of this or child elements.

  • Default is an empty list (no additional offsets).

dy#

The vertical offsets to be applied to each character’s position.

  • A list of space- or comma-separated lengths (with units or as numbers of user units) or percentages (of the coordinate system width).

  • Values are assigned to individual characters in the text content of this or child elements.

  • Default is an empty list (no additional offsets).

rotate#

A rotation to be applied to each character.

  • A list of space- or comma-separated numbers, representing angles in degrees.

  • Values are assigned to individual characters; however, a final value is repeated as necessary for all remaining characters within this element or its children.

  • Default is the single value 0.

textLength#

The expected or desired total offset length of this text element, including all child content.

  • A length (with units or as numbers of user units).

  • Default is to use the textLength computed by the browser, without adjustment.

  • Browser behavior is inconsistent when the text element has child elements.

lengthAdjust#

The parts of the text that the browser may modify if required to match the textLength value.

  • One of the values spacing (adjust letter and word-spacing) or spacingAndGlyphs (stretch or compress individual characters).

  • Default spacing.

<tspan> #

A section of text content with distinct styles or positioning attributes.

Attributes are the same as for <text> except for the following differences:

  • Any values for a given character for x, y, dx, dy, or rotate supercede values specified for the same character on parent elements.

  • The defaults for x and y are empty lists: no absolute positioning is applied.

<textPath>#

A section of text that should be arranged along the outline of a path.

A reference to the path that should be used to position the text.

  • See the definition of xlink:href in the "Repeated Attributes" section.

  • The URL must include a target fragment that matches the id of a <path> element. SVG 2 allows links to any shape element.

  • Theoretically, the <path> could be in a different document, but this has limited support.

  • If not specified, or if the <path> cannot be located, the text content will not be drawn.

startOffset#

The position along the path at which to anchor the text.

  • A length (with units or as a number of user units) measured from the start of the path, or a percentage of the path’s length.

  • Default 0.

  • Browsers are inconsistent about whether startOffset affects absolute (x) position changes.

method#

Whether the browser should align individual characters along the path, or stretch them around curves while maintaining connections between them. No effect in web browsers currently.

spacing#

A hint to the browser on whether the letter-spacing, when converted from straight-line text to the curved path, should be exact (default) or whether optimizations can be used to space letters more attractively (auto). No effect in web browsers currently.

side#

New in SVG 2. When supported, it would effectively reverse the path, positioning text on the opposite side of the line. Value is left (the default, on the left side when facing in the normal direction of the path), or right.

path#

New in SVG 2. When supported, would allow you to define the path data directly on this element, instead of through a separate <path> element. The value would be a path data string, equivalent to the d attribute on a linked <path>.

Document Structure Elements#

The following elements (listed in alphabetical order) create the structure of an SVG file, without defining any vector graphics directly. They establish and alter coordinate systems, create cross-references, or duplicate content from other files or parts of the same file.

<a> #

A hyperlink. Behaves mostly the same as <a> links in HTML.

You should normally add CSS or SVG styles to clearly indicate that this is interactive content. By default, most browsers change the mouse cursor when it is over a link, but do not otherwise distinguish linked content (unlike in HTML, where link text is by default blue and underlined).

The target of the link, as a file and/or a target fragment.

  • Syntax and namespace requirements defined in the "Repeated Attributes" section.

  • If not included, the <a> element has no special functionality; it operates essentially as a <g> grouping element (or as a <tspan> if inside a <text> element).

target#

The name of the browsing context that should be used to display the linked content; a browsing context could be a tab/window in the browser or it could be an iframe or object within the web page.

  • Either a custom name or one of the following keywords:

    • _self (load the linked content in the browsing context that contains the link),

    • _parent (load the linked content in the browsing context that contains the current document, if it exists and can be securely accessed by the current document, or in the current context otherwise),

    • _top (load the linked content in the main browser window or tab that contains this document, if security restrictions do not prevent it),

    • _blank (load the linked content in a new, unnamed browser window or tab).

  • The SVG 1.1 specifications also introduced a keyword _replace, but this is not well supported; the distinction between _self and _replace has been made redundant by changes in the way that browsing contexts are defined in HTML.

  • If a custom name is used, and there is no browsing context by that name previously established by the same web site, a new tab or window is created with that name.

  • Default _self.

<defs> #

A section of the SVG file used for defining content for re-use; the content of the <defs> element is never drawn directly.

<g> #

A group or container for other drawing elements and descriptive content (such as <title>. The <g> element has no unique attributes, but it can be used to transform the coordinate system or declare styles; some graphical effects will apply to the group as a whole, after combining the child content, while others will be inherited by child content.

<image> #

An embedded image file, which may be either SVG or bitmap. SVG viewers are expected to support PNG and JPEG images, but may also support others; browsers generally support the same types of embedded images in SVG as in HTML.

The (relative or absolute) URL of the file to embed.

x, y, width, and height#

Define the layout rectangle in which to position the contents of the image.

  • See the definitions in the "Repeated Attributes" section.

  • An auto value of width or height, in SVG 2, means to use the image file’s intrinsic width or height, or to generate the width and height based on the image’s aspect ratio and a non-auto other dimension.

preserveAspectRatio#

The scaling and alignment strategy that should be used when the intrinsic aspect ratio of the image file does not match the aspect ratio of the image area.

  • Syntax is defined in the "Repeated Attributes" section.

  • The defer keyword may optionally be specified at the beginning of the value; this indicates that if the embedded file is an SVG and the root element has a preserveAspectRatio attribute, its value should be used instead. This has been removed in SVG 2.

externalResourcesRequired#

Indicates whether the external file is an essential part of the main graphic.

  • The value should be either false or true.

  • If true, the main SVG file will not be considered to have loaded (the load event will not fire, and animation timelines will not start) until the external file has fully loaded.

  • Default false.

  • Removed in the SVG 2 specifications; test carefully if the delayed events are important.

crossorigin#

New in SVG 2. Whether the browser should request the image file with cross-origin permissions.

  • Values and impact defined in the "Repeated Attributes" section.

  • Cross-origin permissions are not required for the image to be displayed; the attribute is only required if the same file will be used in scripts or other active content that need permission.

<svg> #

A drawing region for SVG content, which establishes a new coordinate system for that region. All SVG content must be contained within an <svg> element. SVG elements can be nested to allow greater control of the coordinate system, including aspect ratio control. By default, content is clipped to the drawing region; this may be changed with the overflow style property.

x, y, width, and height#

Define the layout rectangle in which to draw the child graphics.

  • See the definitions in the "Repeated Attributes" section.

  • x and y only have an effect for nested <svg>.

  • Default for width and height (in SVG 1) is 100%, but that is only used for nested <svg> and for the root <svg> of a standalone SVG file viewed direcly.

  • Default sizes for inline SVG and for embedded SVG in HTML are much more complex, using the CSS sizing algorithm with no intrinsic size (for that dimension).

  • An auto value for width and height (in SVG 2) behaves like the SVG 1.1 default.

viewBox#

The dimensions of the coordinate system that will be fit to the drawing region.

preserveAspectRatio#

The scaling and alignment strategy to use when the aspect ratio defined by the viewBox does not match the aspect ratio of the drawing region.

<switch> #

Defines a set of possible markup options, only one of which should ever be rendered at a time. Can be used to create fallbacks in certain (limited) situations, or to create multi-lingual content.

The <switch> element itself does not have any unique attributes. Instead, conditional attributes (systemLanguage, requiredFeatures, or requiredExtensions: see the "Common Attributes" section) on child elements determine whether or not they should be rendered.

The first direct child of <switch> which doesn’t have any failing conditional attributes is rendered; all others are then ignored. To be sure that something will always render, include a final child element with no conditional attributes.

<symbol> #

A scalable graphic intended for re-use with the <use> element; content of <symbol> is never drawn directly. By default, content is clipped to the drawing region established by the <use> element; this may be changed with the overflow style property on the <symbol>.

viewBox#

The dimensions of the coordinate system that will be fit to the drawing region established by the <use> element.

preserveAspectRatio#

The scaling and alignment strategy that should be used when the aspect ratio defined by the viewBox does not match the aspect ratio of the drawing region defined for the <use>.

x, y, width, and height#

New in SVG 2. Would have the same effect as on a re-used <svg> element.

refX and refY#

New in SVG 2. Define an reference point within the internal (viewBox) coordinate system of the symbol. The re-used symbol would be offset such that this reference point is positioned over the x, y point of the <use> element.

<use> #

A graphical instance of content defined elsewhere (in the same file or another file on the same web domain), that will be redrawn at the specified position. The duplicated graphical content inherits any styles applicable to the <use> element according to the normal rules of style inheritance, but is also subject to all styles defined directly on the original graphics elements.

a URL reference to the target element which will be duplicated.

  • Syntax and namespace requirements defined in the "Repeated Attributes" section.

  • Older browsers do not support references to external files; as of SVG 2, there is no support for cross-origin references.

x#

The horizontal offset to add to the coordinate system origin before positioning the duplicated content

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 0.

  • Treated as a coordinate system translation for any graphical effects on the <use> element (applied after any transform transformation).

y#

The vertical offset to add to the coordinate system origin before positioning the duplicated content

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 0.

  • Treated as a coordinate system translation for any graphical effects on the <use> element (applied after any transform transformation).

width and height#

The dimensions of the layout rectangle in which to fit the viewBox dimensions of re-used <svg> or <symbol> content.

  • Syntax as defined in the "Repeated Attributes" section.

  • Default 100%, unless the <use> element references an <svg> that has a specified width value, in which case that value will be used as a default.

  • Has no effect when re-using other types of content.

<view> #

A pre-defined alternate view of the SVG document. A <view> element is used by referencing the element’s id as the target fragment of a URL.

viewBox#

The dimensions of the coordinate system that will be fit to the drawing region; replaces the equivalent attribute on the <svg>.

preserveAspectRatio#

The scaling and alignment strategy that should be used when the aspect ratio defined by the viewBox does not match the aspect ratio of the drawing region; replaces the equivalent attribute on the <svg>.

viewTarget#

A whitespace-separated list of id values for the elements that are the main focus of the view (removed in SVG 2).

Elements for adding other languages to SVG#

SVG is designed to work with CSS, JavaScript, HTML, and other XML languages. The following SVG elements are used to integrate code from those languages in your SVG markup.

See also Metadata Elements.

<style>#

An embedded stylesheet that should apply to the elements in this document. The text content is parsed as a CSS stylesheet. In XML documents, you can use a <![CDATA[…]]> wrapper around the text to prevent errors from text characters that have special meaning in XML.

The SVG <style> element is very similar to the HTML <style> element, but they create different DOM objects with slightly different properties. SVG 2 adds the CSS OM sheet property to allow you to directly access the stylehseet object, but older browsers may not support it.

See Chapter 3 in the book for details on how to link external stylesheets.

type#

The type of stylesheet language, as a media type (MIME type) string.

  • Value should usually be text/css, if the attribute is used at all.

  • Default in web browsers and SVG 2 is text/css, but some other software doesn’t apply a default.

  • If your software isn’t applying any of your CSS, try adding type="text/css" to your <style> element.

media#

A media query condition that determines whether this stylesheet applies (see Chapter 3 in the book for more on media queries and SVG).

  • Default is all, meaning the stylesheet always applies.

title#

A name for the stylesheet. Used by software that supports alternative stylesheets, but that is pretty rare these days.

<script>#

An embedded or linked script to run within the current document’s scope, if the SVG is being rendered in an environment that supports scripting. In XML documents, always use a <![CDATA[…]]> wrapper around embedded script code, to prevent parsing errors.

The SVG <script> element is very similar to the HTML <script> element, but they create different DOM objects with slightly different properties.

type#

The type of scripting language, as a media type (MIME type) string.

  • Default is application/ecmascript (which should be equivalent to text/javascript in most browsers).

  • Other values are allowed. Unrecognized script types cause the script to be ignored—​which can sometimes be useful. For example: type="text/json" can be used to include JSON data in the markup without parsing it, so that another script can access it by reading this element’s text content.

The URL of an external script file (equivalent to src on an HTML <script> element).

crossorigin#

New in SVG 2. Whether the browser should request an external script file with cross-origin permissions.

  • Values and impact defined in the "Repeated Attributes" section.

  • Cross-origin permissions are not required for normal script execution, only if other scripts need to access this file’s data.

<foreignObject>#

A container element for non-SVG elements which should be rendered and inserted into the SVG drawing. The element defines a rectangular area in the SVG coordinate system; the foreign content will be positioned in this rectangle.

When the SVG is inline in HTML, the HTML parser treats the child content of <foreignObject> the way it treats regular HTML content: as HTML elements unless it is <svg> or <math>. In XML documents, use XML namespaces on the child content to indicate its type.

x, y, width, and height#

Define the layout rectangle in which to render the foreign content.

  • See the definitions in the "Repeated Attributes" section.

  • Default for width and height (in SVG 1) is 0, which disables rendering; the SVG 2 auto value behaves the same.

<audio>, <video>, <iframe>, and <canvas>#

New in SVG 2. These HTML elements (with correct namespacing in XML documents) could be directly added to SVG, positioned in a layout rectangle defined by the new x, y, width, and height geometry properties (not attributes). For now, use <foreignObject> to embed these elements.

Paint Server Elements and Markers#

The following elements and attributes are used to define SVG paint servers and markers, to control the appearance of other elements. In SVG 1, the main pattern, gradient, or marker element requires an id attribute that is used by reference in other element’s style properties. In SVG 2, the reference could instead be defined using a parent-child relationship.

Paint servers are used by reference in the fill and stroke properties of shapes and text.

Markers are referenced in the marker property and its longhands (marker-start, marker-mid, and marker-end). In SVG 1.1, they only apply to certain shape elements (<line>, <path>, <polygon>, and <polyline>); in SVG 2, they would apply to all shapes.

<linearGradient> #

A gradient in which color stops are drawn as parallel lines, extending perpendicularly (in the current coordinate system) from a gradient vector.

x1#

The horizontal position of the gradient vector’s start point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width)

  • Default 0.

y1#

The vertical position of the gradient vector’s start point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height)

  • Default 0.

x2#

The horizontal position of the gradient vector’s end point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width)

  • Default 100%.

y2#

The vertical position of the gradient vector’s end point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height)

  • Default 0.

gradientUnits #

The coordinate system to use.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default objectBoundingBox.

gradientTransform #

Transformations to apply to the gradient content, independent of the shape it fills.

spreadMethod #

The strategy to use for filling content beyond the start and end of the gradient vector.

  • One of pad, reflect, or repeat.

  • Default pad.

A reference to another gradient which should be used as a template for this one..

  • Syntax and namespace requirements defined in the "Repeated Attributes" section.

  • The URL must have a target fragment that matches a <linearGradient> or <radialGradient> element.

  • Cross-file references are not well supported in web browsers.

  • All attributes on the referenced element become the default values for the current element.

  • If the current element does not contain any <stop> elements, then the stops from the referenced element will be used.

<marker> #

A self-contained graphic to be positioned at the points of a custom shape, using the marker-start, marker-mid, or marker-end properties of that shape.

markerUnits#

The coordinate system scaling to use for the marker width and height; also defines the coordinate system scale if a viewBox is not specified.

  • Either strokeWidth or userSpaceOnUse.

  • Default strokeWidth.

refX#

The horizontal position, within the marker coordinate system, of the reference point which should be aligned with the marked point on the shape.

  • A number of user coordinates.

  • Default 0.

refY#

The vertical position, within the marker coordinate system, of the reference point which should be aligned with the marked point on the shape.

  • A number of user coordinates.

  • Default 0.

markerWidth#

The width of the marker region.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 3.

  • Negative values are an error.

markerHeight#

The height of the marker region.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 3.

  • Negative values are an error.

orient#

The rotation to be applied to the marker, relative to the coordinate system of the shape it is marking.

  • Either auto (based on the tangent of the line) or a number of degrees (relative to the x-axis).

  • SVG 2 adds auto-start-reverse (a start marker will be rotated 180°, so you can use the same marker for start and end) and angles with units.

  • Default 0.

  • Rotations are always relative to the reference point that is aligned with the marked corner.

  • Browsers are inconsistent with auto-oriented midpoint markers where there are open subpaths or zero-length path segments.

viewBox #

declaration of a custom coordinate system to use for the marker contents

  • Syntax as defined in the "Repeated Attributes" section.

  • By default, the coordinate system has the origin at the top left corner of the marker region, with a unit scale as defined by markerUnits.

  • The viewBox is implemented as a scaling transformation, and does not create a new reference definition for percentage lengths (although browsers are inconsistent about this).

preserveAspectRatio #

The scaling and alignment strategy that should be used when the aspect ratio defined by the viewBox does not match the aspect ratio of the marker region

<pattern> #

A paint server that defines a region of custom SVG content that should be used to fill other elements, repeating it as necessary in a rectangular grid.

x, y, width, and height#

The dimensions and offset-position of the reference pattern tile.

patternUnits #

The coordinate system to use for x, y, width, and height

  • Either userSpaceOnUse or objectBoundingBox

  • Default objectBoundingBox

patternContentUnits #

The coordinate system to use for drawing the child content of the pattern

  • Either userSpaceOnUse or objectBoundingBox.

  • Default userSpaceOnUse.

  • Has no effect if a viewBox is specified.

  • A value of objectBoundingBox is implemented as a non-uniform scale to the user units. It does not create a new reference definition for percentage lengths.

viewBox #

Declaration of a custom coordinate system to use for the pattern contents.

  • Syntax as defined in the "Repeated Attributes" section.

  • By default, the coordinate system is controlled by patternContentUnits.

  • The viewBox is implemented as a scaling transformation, and does not create a new reference definition for percentage lengths.

preserveAspectRatio #

The scaling and alignment strategy that should be used when the aspect ratio defined by the viewBox does not match the aspect ratio of the pattern tile.

patternTransform #

Transformations to apply to the pattern tiles and their content, independent of the shape it fills.

A reference to another pattern which should be used as a template for this one.

  • Syntax and namespace requirements defined in the "Repeated Attributes" section.

  • The URL must have a target fragment that matches the ID of a <pattern> element.

  • Cross-file references are not well supported in web browsers.

  • All attributes on the referenced element become the default values for the current element.

  • If the current element does not contain any child elements, then the pattern content from the referenced element will be used.

<radialGradient> #

A gradient in which color stops are drawn along rays from a starting point to an ending circle.

cx#

The horizontal position of the center-point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default 50%.

cy#

The vertical position of the center-point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default 50%.

r #

The radius of the circle.

  • A length (in user coordinates or with units) or percentage (proportional to the coordinate system diagonal length, as defined in the Units guide).

  • Default 50%.

  • Negative values are an error.

fx#

The horizontal position of the focal point.

  • A length (in user coordinates or with units) or percentage (of coordinate system width).

  • Default is to match cx.

fy#

The vertical position of the focal point.

  • A length (in user coordinates or with units) or percentage (of coordinate system height).

  • Default is to match cy.

gradientUnits #

The coordinate system to use.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default objectBoundingBox.

gradientTransform #

Transformations to apply to the gradient content, independent of the shape it fills.

  • Syntax and options are the same as same as for <linearGradient>.

spreadMethod #

The strategy to use for filling content beyond the ending circle.

  • Syntax and options are the same as for <linearGradient>.

A reference to another gradient which should be used as a template for this one.

  • Syntax and options are the same as same as for <linearGradient>.

<stop> #

A defined value within the gradient.

offset#

The distance along the gradient vector or ray at which to position this value

  • A number between 0 and 1, or a percentage.

  • Valueswill be clamped to the range [0-1] or [0%-100%].

  • Stops must be listed in order of increasing offsets; if not, the offset will be adjusted to match the previous maximum value.

  • Default 0 was added in SVG 2; it’s well-supported in browsers, but some older tools may treat a missing offset as an error.

stop-color (presentation attribute) #

The color to use at this stop point.

  • Any valid color definition supported by the browser.

  • Default black.

  • Browsers are inconsistent about semitransparent colors.

stop-opacity (presentation attribute) #

The alpha value to use at this stop point.

  • A number between 0 and 1.

  • Default 1.

  • SVG 2 allows percentage values.

path#

New in SVG 2. Used for mesh gradients to describe the path segment leading to this color stop (instead of offset).

<meshgradient>, <meshrow>, and <meshpatch>#

New in SVG 2. Define the grid structure of mesh gradients. The <stop> elements inside each <meshpatch> define the actual shape and colors of the gradients.

<hatch> and <hatchpath>#

New in SVG 2. Define a hatch pattern, defined by repeating sections of a stroked path (or paths) instead of by tiled graphics.

<solidcolor>#

New in SVG 2. Defines a single color that can be reused as a paint server. Was called <solidColor> in SVG Tiny 1.2.

Clipping and Masking Elements#

The <clipPath> and <mask> elements define custom clipping path and mask graphical effects within SVG markup. They require an id attribute which can by used by reference from the clip-path or mask style properties, respectively.

<clipPath> #

A container for a vector shape or collection of vector shapes that can be used as a clipping path to limit the rendered and interactive region of another. Allowed child elements are shape elements, <text>, and <use> elements that directly reference a shape or text element.

clipPathUnits#

The coordinate system to use for the content of the <clippath> element.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default userSpaceOnUse.

<mask> #

A container for SVG graphical content that defines an image that will be used as a mask for the referencing object.

maskUnits#

Defines the coordinate system for the x, y, width and height attributes.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default objectBoundingBox.

maskContentUnits#

Defines the coordinate system for the child content of the <mask>.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default userSpaceOnUse.

  • A value of objectBoundingBox is implemented as a non-uniform scale to the user units, it does not create a new reference definition for percentage lengths.

x, y, width and height#

Define the outer limits of the mask as a rectangle; any parts of the masked graphic that extend outside this rectangle will be clipped completely.

  • See definitions in the "Repeated Attributes" section.

  • Defaults for x and y are -10%; defaults for width and height are 120%.

  • Valuesare scaled according to maskUnits

  • Percentages are a percentage of the bounding-box or user-space height or width, accordingly.

  • Lengths with units only make sense when maskUnits is userSpaceOnUse

mask-type (presentation attribute)#

New in SVG 2/CSS3. Whether the mask contents should be treated as a luminance mask or alpha mask by default.

  • Allowed values alpha or luminance.

  • Default is luminance.

  • The value can be over-ridden by the mask-mode property of the element using this mask.

  • Both mask-type and mask-mode are added by the CSS Masking Module, and have limited support. In SVG 1, all masks were luminance masks.

Filter Elements#

The SVG filter elements can be divided into the <filter> element itself, its children filter primitive elements (which apply the individual filter manipulations), and secondary primitive elements which are only valid as children of a particular primitive.

This reference covers the attributes for the elements described in Chapter 16 in the book, plus a few others which can be explained in brief. The remaining elements are described so that you know what they can do, but the specific attributes are not detailed here. The full Filter Effects specification is available online.

The filter primitive elements have some shared attributes. Specific behavior is described for each element, but these are the shared features:

x, y, width, and height#

The top-left offset and dimensions for the filter primitive (clipping) region for this element’s result.

  • Default is to match the combined region from the primitive’s inputs, or the <filter> element’s filter effects region for the first primitive.

  • Values are scaled according to primitiveUnits on the parent <filter> (userSpaceOnUse by default).

result#

A name for the output of this element, so it can be referenced as an input to later steps in the filter.

  • Should be a single-word identifier.

  • Case-sensitive.

  • Can’t be one of the filter input keywords.

  • Must be unique within a given <filter> element.

in and in2#

The input image layers which will be used by this element; how the inputs are used depends on the element. Default for both input attributes is to use the output from the previous filter in the chain, or the source graphic if this is the start of the chain. Allowed values are:

  • A name given in the result attribute for a previous filter primitive in the same <filter> element.

  • SourceGraphic, the flattened image layer for the element with the filter property or, if the url() reference to this filter was part of a chain, the result of the previous filter in the chain.

  • SourceAlpha, the result of removing all color from the SourceGraphic (setting R, G, and B to 0) so that only transparency variations remain.

  • BackgroundImage, the result of compositing all previous elements (lower layers in the z-index stack) ever since the last parent element that has isolation (explicit or automatic) or enable-background: new.

  • BackgroundAlpha, an alpha-only version of the background image.

  • FillPaint, a theoretically-infinite layer consisting of whatever color or paint server is set in the fill property of the filtered element, scaled to that element.

  • StrokePaint, equivalent to the fill paint layer, but using the color or paint server from the stroke property.

The last four inputs are not currently well-supported in web browsers, and may be treated as a failing error.

The specific elements and their attributes are described in the rest of the section. The <filter> element is defined first, then the remaining elements are sorted in alphabetical order:

<filter>#

A complete filter effect that can be applied to other elements. It requires an id attribute that is used to reference it from another element’s filter property.

x, y, width, and height#

The top-left offset and dimensions of the filter effects region as a rectangle; any parts of the filter results that extend outside this rectangle will be clipped (including any parts of the original graphic).

  • See definitions in the "Repeated Attributes" section.

  • Defaults for x and y are -10%; defaults for width and height are 120%.

  • Values are scaled according to filterUnits.

  • Percentages are a percentage of the bounding-box or user-space height or width, accordingly.

  • Lengths with units only make sense when filterUnits is userSpaceOnUse.

filterUnits#

The scaling to use for the filter effects region.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default objectBoundingBox.

primitiveUnits#

The scaling to use for specified attributes on the child filter primitive elements, including the filter primitive regions.

  • Either userSpaceOnUse or objectBoundingBox.

  • Default userSpaceOnUse.

<feBlend>#

Combines two inputs using blending modes, which mathematically combine the colors of pixels.

in#

The input that will be layered on top.

in2#

The input that will be used as the backdrop.

mode#

The blending mode to use.

  • One of the 16 blending mode keywords listed in the Blend Modes Reference (only 5 of which were defined in SVG 1.1).

  • Default normal.

<feColorMatrix>#

Performs color modifications which can’t be separated out into different calculations for each channel (red, green, blue, and alpha), but instead work on their combined values.

in#

The single input that will be modified.

type#

The type of modification to apply.

  • One of the keywords matrix, saturate, hueRotate, luminanceToAlpha

  • Default matrix.

values#
  • Ignored for the luminanceToAlpha type.

  • For saturate type, a single number value representing relative saturation (1 is no change, 0 is grayscale).

  • For hueRotate type, a single number value representing rotation around the color circle in degrees (0 and multiples of 360 mean no change).

  • For matrix type, a 20-number list (separated by whitespace and/or commas). For an introduction to the matrix values, see "Color Filters Can Turn Your Gray Skies Blue", by Amelia Bellamy-Royds on CSS-Tricks.

<feComponentTransfer>#

Performs color manipulations on each color channel (red, green, blue, and alpha) separately. The changes to be made are defined by <feFuncR>, <feFuncG>,<feFuncB>, and <feFuncA> elements, which are direct children of this element. The element should only have one child element of each type. Any of the child elements can be left out, in which case that channel isn’t modified.

in#

The single input that will be modified by the child elements.

<feComposite>#

Combines two inputs by dividing them into opaque and transparent regions with semi-opaque regions getting partial effects.

The operators names should be read as in [operator] in2.

in#

The layer that will be on top (the "source" in the compositing definitions).

in2#

The layer that will be the backdrop (the "destination" in the compositing definitions).

operator#

The way the two layers will be merged.

  • One of 7 keywords:

    • over (layer in over in2, like normal alpha compositing),

    • in (use the parts of in that are inside opaque (or semi-opaque) regions of in2, creating(an alpha-mask effect),

    • out (use the parts of in that are outside the opaque regions of in2),

    • atop (layer in over in2, and then clip the combination to only include the parts that are inside in2),

    • xor (use the parts of in that are outside in2, and the parts of in2 that are outside in),

    • lighter (add the pixel values for in and in2 together, scaled by their alpha values; this value is new in CSS3, and may not be supported everywhere),

    • arithmetic (perform a custom mathematical calculation to combine the two layers; the same calculation will be applied independently to each of the channels—​red, green, blue, and alpha; useful to create cross-fades or dissolves of one layer into the other).

  • Default over.

k1, k2, k3, and k4#

Numerical constants to use for the arithmetic formula.

  • The equation is k1×i1×i2 + k2×i1 + k3×i2 + k4, where i1 is the pixel value from in1 and i2 is the pixel value from in2.

  • The defaults for all factors are 0, so an arithmetic operator will create a transparent black result if you don’t set at least one of these attributes to a positive value.

  • For a cross-fade or disssolve effect, k2 and k3 should add up to 1.

  • For adding the results of a <feSpecularLighting> operation (as in) on top of a base image (as in2), k2 should be a value between 0 and 1 (depending on the intensity of light you want to create), and k3 should be 1 (so the original image stays opaque).

<feConvolveMatrix>#

Modify each pixel by using a formula based on the values of its neighboring pixels. Each channel (R, G, B, and A) is modified independently based on the same matrix formula. Can be used to create directional blur effects, or edge detection effects. Consult the specs for attribute descriptions.

<feDiffuseLighting>#

Calculates a pattern of light and shadow that would apply to a 3D-surface. The end result is an opaque layer representing light and shadow; this layer would then normally be blended onto an actual image layer using screen, overlay, hard-light, or soft-light modes.

Like <feSpecularLighting>, it takes one (in) input, whose alpha values are used as a "bump map" representing the relative heights of the surface being lit; the colors of the input are ignored. The color of the light is set by the lighting-color style property. Consult the specs for other attribute descriptions.

This element requires a single light-source element as a child: one of <feDistantLight>, <fePointLight>, or <feSpotLight>.

<feDisplacementMap>#

Distorts one input by shifting its pixels by amounts defined by the colors in a second input (the displacement map). Ideally, the browser will smooth out the effect by blending colors between pixels, but it depends on the browser.

in#

The image layer to distort.

in2#

The map describing the amount of distortion.

xChannelSelector and yChannelSelector#

which color channel from the map should be used to determine the horizontal (x) or vertical (y) displacement.

  • One of R, G, B, or A.

  • Default for both is A.

  • Displacement will be zero for pixels where the input channel is 50%.

scale#

The distance between the maximum positive and negative displacement; no pixels will be moved more than half the scale distance from their starting point.

  • A positive number or 0.

  • Default is 0, which means no displacement.

<feDistantLight>#

A light source to be used as a child of <feDiffuseLighting> or <feSpecularLighting>. Distant light is light that comes from so far away that the light beams are effectively parallel, rather than radiating out from a point. For example, sunlight would be distant light. The light source is defined by the angle of the light, measured in two different components: the angle above the surface (e.g. sunrise/sunset versus high noon) is the elevation; the angle parallel to the surface (e.g. east for sunrise versus west for sunset) is the azimuth. Consult the specs for full attribute descriptions.

The color (both hue and brightness) of light is determined by the lighting-color style property or presentation attribute on the parent element.

<feDropShadow>#

Generate a drop shadow for the input layer: a blurred, colored, and optionally offset copy of the input’s alpha channel, which is layered behind the original input.

This element was added in the Filter Effects module and won’t be supported in older software; it can be replaced by a sequence of steps using <feGaussianBlur>, <feFlood>, <feOffset>, and <feComposite>.

stdDeviation#

The amount of blur to apply to the shadow.

  • Equivalent to stdDeviation on <feGaussianBlur>.

dx and dy#

How far to offset the shadow layer from the original shape.

  • Equivalent to dx and dy on <feOffset>.

flood-color and flood-opacity (presentation attributes)#

The color and opacity of the shadow (prior to blurring).

<feFlood>#

Generates a layer of continuous color that completely fills this element’s filter primitive region.

flood-color and flood-opacity (presentation attributes)#

The color and opacity of the new layer.

<feFuncR>, <feFuncG>,<feFuncB>, and <feFuncA>#

transfer functions that change the values of one of the color channels (R, G, B, or A, respectively) in the input to this element’s parent <feComponentTransfer> element. The calculations are all made after converting the color channels to the range 0 to 1, where 1 is 100% in an rgba() representation of the color. After the calculation, each values is clamped to be no less than 0 or greater than 1.

These elements can only be used as a child of <feComponentTransfer>.

type#

The type of mathematical function to use.

  • One of identity, table, discrete, linear, or gamma.

  • The other attributes depend on the type selected.

  • Default identity, which doesn’t change anything.

  • table means divide up the input range into equal intervals, map the dividing points to new values, and scale all the values in between in a linear change; useful for inverting colors and for converting almost-black / almost-white to perfect black and white.

  • discrete means divide up the input range into equal intervals, and map each block to new values; useful for converting smoothly-transitioning colors (e.g., in a photograph) into solid color regions (a posterize effect).

  • linear means calculate the output value using a straight-line equation, multiplying the input by a slope factor, then adding a constant intercept.

  • gamma means calculate the output value using a curved function: the input raised to the power of an exponent, multiplied by an amplitude, and then with an offset added.

tableValues#

For table and discrete functions, the new values to use.

  • A list of numbers, which are normally between 0 and 1 (but can be outside that), separated by whitespace or commas.

  • There must be at least 2 values for table, and at least one value for discrete.

slope#

For linear functions, the factor used to multiply the input-value.

  • A number.

  • Default 1 (which means the change is determined only by intercept).

  • Values between 0 and 1 reduce the color; values greater than 1 increase it; negative values invert the colors.

intercept#

For linear functions, a constant value added to the result.

  • A number.

  • Default 0 (which means the change is determined only by slope).

  • Positive values brighten the color, negative values darken it.

amplitude#

For gamma functions, the multiplicative factor used in a gamma function.

  • A number.

  • Default 1 (which means the change is determined by exponent and offset).

  • Values are equivalent to slope in a linear function.

exponent#

For gamma functions, the exponential factor used on the input value.

  • A number.

  • Default 1 (which means the change is determined by amplitude and offset).

  • Values are the inverse (1/x) of those commonly used in graphics software to describe gamma levels.

  • Values greater than one make the result darker; values less than 1 make the result brighter (in this color channel).

offset#

For gamma functions, the constant value added to the result.

  • A number.

  • Default 0 (which means the change is determined by amplitude and exponent).

  • Values are equivalent to intercept in a linear function.

<feGaussianBlur>#

Performs a smooth blur.

in#

The single input layer to modify.

stdDeviation#

The standard deviation of the Gaussian function; the "edge" of the blur will be approximately two standard deviations from the original edge of a shape or color block, with some color extending three standard deviations away.

  • One number for a uniform blur, or two numbers for separate blur distances in horizontal and vertical directions.

  • Both numbers must be 0 or positive values.

  • Default 0, which means no blurring.

  • Lengths are scaled according to primitiveUnits: as user units by default, or as fractions of the object bounding box.

edgeMode#

How to fill in extra pixels at the edge of the input layer, before blurring

  • One of none (fill in with transparent black), duplicate (copy the pixel color from the edge of the layer), or wrap (use the pixels from the opposite edge of the layer).

  • Default none.

  • New in CSS3; not well supported in browsers.

<feImage>#

Imports a separate image file (or data URI) as a filter layer.

Can also be used to clone an element from the document (similar to <use>) as a filter layer. However, Firefox does not support this, and the details aren’t well defined in the specs.

The URL of the image file; same as for <image>; can also reference an element in this file (similar to <use>), but that isn’t well-defined and is not supported in Firefox.

crossorigin#

New in SVG 2. Whether the browser should request the image file with cross-origin permissions.

  • Values and impact defined in the "Repeated Attributes" section.

  • Cross-origin permissions are required if this image is from another domain and will be used as the input for filter primitives that manipulate pixel data.

x, y, width, and height#

Set the size and position of the image; note that the defaults are the same as for other filter primitives. If you never change the default dimensions, the image will be -10% offset from the top left corner of the object bounding box.

preserveAspectRatio#

Sets the scaling method to use if aspect ratios don’t match; same as for <image>.

<feMerge> and <feMergeNode>#

Layers any number of inputs together with normal alpha compositing. The inputs are specified with <feMergeNode> elements that are children to the <feMerge>. The order of <feMergeNode> elements becomes the order of layers, from bottom to top.

in on <feMergeNode>#

The input to add to the stack; if not specified, the default input for the <feMerge> element is used.

<feMorphology>#

When applied to an alpha-only layer, this causes the edges to grow (dilate) or shrink (erode). When applied to complex colors or photographs, it creates a blocky, impressionist-painting effect.

in#

The input layer to modify.

operator#

The type of morphology to apply.

  • Either erode or dilate.

  • Default erode.

radius#

The size of the rectangle to use for identifying neighbor pixels, as a distance from the target (center) pixel.

  • One number or two, for separate horizontal and vertical distance.

  • Must be positive.

  • Default is 0, which means no pixels will be changed.

  • The radius distances are scaled according to primitiveUnits: as user units by default, or as fractions of the object bounding box.

<feOffset>#

Shift the input layer horizontally and/or vertically, without distorting it or changing any pixels (except perhaps by clipping it to the filter primitive region).

in#

The input layer to be offset.

dx and dy#

The distance to translate on the x and y axes, respectively.

  • Value for each is a single number without units.

  • Negative (left/up) or positive (right/down) distances are possible.

  • Default for both is 0, which means no movement in that direction.

  • The distances are scaled according to primitiveUnits: as user units by default, or as fractions of the object bounding box.

<fePointLight>#

A light source to be used as a child of <feDiffuseLighting> or <feSpecularLighting>. A point light radiates light out in all directions. It is defined by its position in 3D space. Consult the specs for attribute descriptions.

The color (both hue and brightness) of light is determined by the lighting-color style property or presentation attribute on the parent element.

<feSpecularLighting>#

Calculates a pattern of glare or "shine" light on a 3D surface. The end result is opaque in sections where there would be glare and transparent in other sections. It would normally be blended on top of the image representing the colors of the surface, or combined using <feComposite> atop or arithmetic operators to add the colors together.

Like <feDiffuseLighting>, it takes one (in) input, whose alpha values are used as a "bump map" representing the relative heights of the surface being lit; the colors of the input are ignored. In addition, the specular effect is defined by a set of constants that represent the "shiny-ness" of the surface. The color of the light is set by the lighting-color style property. Consult the specs for other attribute descriptions.

This element requires a single light-source element as a child: one of <feDistantLight>, <fePointLight>, or <feSpotLight>.

<feSpotLight>#

A light source to be used as a child of <feDiffuseLighting> or <feSpecularLighting>. A spot light is a cone of light with clear edges. It is defined by the 3D position of the light source, the direction it is pointing, the angle of the cone, and how tightly the light is focused in the center of the cone relative to its edges. Consult the specs for attribute descriptions.

The color (both hue and brightness) of light is determined by the lighting-color style property or presentation attribute on the parent element.

<feTile>#

Repeats the input layer in a row-and-column tiling pattern.

In order to have any effect, this element’s filter primitive region must be larger than that of its input.

in#

The layer to be used as the pattern tile.

x, y, width, and height#

Set the final size of the region to be covered with the repeated tile.

<feTurbulence>#

Generates a region of Perlin noise. The end result has all four channels (red, green, blue, and alpha) distributed between 0 and 100% in continuously changing levels that appear like natural variation in a material.

type#

Defines the algorithm to use to generate the colors.

  • fractalNoise creates a more splotchy effect.

  • turbulence (the default) creates a more swirling effect.

baseFrequency#

The frequency at which colors change, measured as the number of oscillations in color per user unit in the user-space coordinate system.

  • One or two positive numbers (one for horizontal and one for vertical frequency).

  • If the user-space scale is close to 1px per screen pixel then you’ll need small decimal numbers to see interesting patterns.

  • smaller numbers create longer "waves" of color changes.

  • A value of 0 in one direction creates stripes in the other direction.

  • Default is 0 in both directions, which results in transparent black for turbulence and half-transparent gray for fractalNoise.

numOctaves#

The number of additional oscillation frequences to stack on the base frequency; extra octaves create more local variation in color, in addition to the main waves.

  • An integer value of at least 1.

  • higher numbers require more processing; numbers greater than 10 won’t have a visible effect on a normal computer monitor.

  • Default is 1.

stitchTiles#

Whether or not the browser should adjust the pattern to have more continuous effects from one edge to the next if the result is used in a tiling pattern.

  • Either stitch or noStitch (the default).

seed#

A number used as the base input for the Perlin noise pattern; different seeds create different final patterns.

  • Default is 0, which isn’t special except that it should give approximately the same result in any browser.

In addition, the processing of many filter primitives are affected by the color-interpolation-filters style property or presentation attribute.

Metadata Elements#

There are three metadata elements in SVG. None of them directly contribute to the visible graphic.

In addition, SVG 2 recommends that the HTML-namespaced <meta> and <link> elements should be supported anywhere in an SVG file. For inline SVG, move them to the HTML <head> section; the HTML parser does not currently recognize them inside of SVG content.

<title>#

A short label for its parent element. A title for the root SVG is used as the document title. A title for a nested SVG, group, or graphical element is usually displayed as a tooltip. For best support, the <title> should always be the first child element of its parent.

<desc>#

A longer description for its parent element. May contain structured markup, such as HTML. However, that structure will not normally be conveyed to assistive technology, even where long descriptions are supported at all.

<metadata>#

A container for arbitrary XML metadata from other namespaces.

In SVG 2, multiple <title> or <desc> elements with different languages (as declared with the lang attribute) would be treated as a system-language switch.

Animation Elements#

There are only four main SVG/SMIL animation elements, but more than two dozen attributes to modify them.

Many animation options only apply if the attribute you are changing can be interpolated to generate in-between values. Some types of animations only apply to additive attributes; that is, they require that two different values can be added together. Single lengths or numbers can be added, as can colors and some x,y paired values.

The following shared attributes are used on most or all of the animation elements, organized into the same categories used in the online tutorial "Using SVG/SMIL Animation Elements":

Setting the target element and attribute#

The target element, as a URL cross-reference to an element in the same document.

attributeName#

The name of the attribute or CSS property to modify.

  • XML attribute names are case sensitive.

  • The name can include an XML prefix (like xlink:href), which is parsed using the prefixes declared in the document markup.

  • Most attributes are animatable, but not all.

attributeType#

Whether to animate an attribute or style property.

  • Either XML, CSS, or auto.

  • Default is auto, which means use CSS if a CSS property exists with the specified name.

Setting the new value(s)#
to#

The final value for the animation.

  • Syntax depends on the attribute being animated.

  • Ignored if values is specified.

by#

A relative amount to change the target animation to create the final value.

  • Syntax depends on the attribute being animated.

  • Only applies to additive attributes.

  • Ignored if to or values is specified.

from#

Sets a starting value for the animation, as an alternative to starting from the base value on the element.

  • Syntax depends on the attribute being animated.

  • Ignored if values is specified.

values#

A list of keyframe values to cycle through over the duration of the animation.

  • Syntax is a semicolon-separated list; the individual values in the list follow the syntax of the attribute being animated.

fill#

Whether or not to hold the final value after the animation ends.

  • Either freeze (hold the value) or remove (the default).

Setting duration and repeats#
dur#

The time duration of a single cycle of the animation.

  • Many possible syntaxes. All of the following equal 3.3 seconds: 3.3, 3.3s, 3300ms, 0.055min, 00:03.3, 00:00:03.3

  • The : versions require two-digit numbers for hours and minutes, but the decimal part is optional.

  • Default is indefinite, which is only useful for <set> animations.

repeatCount#

The number of times to repeat the animation cycle.

  • Any positive number (including decimals for partial repeats), or indefinite for theoretically infinite repeats.

  • Default is no repeats.

  • The actual repeat number will be limited by repeatDur, end, and max.

repeatDur#

The total time to repeat the animation cycle.

  • A time (with the same syntaxes as dur) or indefinite for theoretically infinite repeats.

  • Default is no repeats.

  • The actual repeat time will be limited by repeatCount, end, and max.

max#

The maximum duration for the animation including repeats.

  • Same syntaxes as dur.

  • Default is no maximum.

min#

The minimum duration (including repeats) before the animation will be ended by an end trigger.

  • Same syntaxes as dur.

  • Default is no minimum.

  • Will not change the basic duration or repeat counts.

Setting beginning and ending times#
begin#

The start times or triggers for the animation.

  • A semicolon-separated list of different triggers.

  • Each begin trigger be specified in any of the following ways:

    • A time (same syntaxes a dur), measured from the document load time or the current time set with the setCurrentTime() method on the nearest ancestor <svg> element.

    • The name of a DOM event (like click or focus) on this animation’s target element.

    • The id of another element in the DOM and a DOM event for that element, like link.mouseover.

    • The id of another animation element, then an animation sync event: begin, end, or repeat(n) where n is an integer for the start of the nth repeat of the specified animation.

    • Any of the event formats, plus or minus a time offset, like focus + 0.3s or flash.end - 700ms.

    • indefinite, which means that the animation will only begin as described below.

  • Animations can also be started if the element’s beginElement() or beginElementAt() methods are called, or if it is the target of a link in the document and that link is activated.

  • If the begin time is negative, or is specified as a negative time offset relative to a DOM event or animation sync event that couldn’t be predicted ahead of time, then the animation will begin partway through.

  • The spec also describes "access key" triggers and "wallclock" triggers (real times based on the system clock), but these aren’t well supported in browsers.

  • Default is 0s.

end#

End times or triggers for the animation.

  • Same syntax and options as begin.

  • Any end trigger will end the current animation; they aren’t neatly paired with begin triggers.

  • Default is indefinite, which means that the end-time is set by the duration, repeats, and max.

restart#

Whether or not to allow a new begin trigger to restart an animation that is currently in process.

  • Options are:

    • always (any begin-trigger will restart the animation from the beginning),

    • whenNotActive (don’t restart if it’s in process),

    • never (the animation will only ever run once).

  • Default is always.

Setting pacing between keyframes#
calcMode#

How to calculate the changing values over the duration of the animation.

  • Options are:

    • linear (change values smoothly so that the % change in value matches the % change in time, for each pair of consecutive keyframes),

    • paced (calculate a total distance required to pass through all the values, and adjust the timing of each keyframe to maintain a constant rate of change through them all; only applies to additive attributes for which a distance can be calculated),

    • spline (use cubic Bézier easing as defined by keySplines),

    • discrete (change from one value to the next in sharp jumps).

  • Default is linear, except for <animateMotion> (where the default is paced).

keyTimes#

The relative position within the animation duration for each value in a values list.

  • A semicolon-separated list of numbers between 0 and 1.

  • There must be as many entries in the list as in the values list, or two entries for animations set with to/by/from.

  • The first time in the list must be 0; the last time in the list must be 1 unless calcMode is discrete.

  • For discrete animations, the keyTimes represent the start time for the value.

  • Default is to divide the duration equally between each interpolation step.

  • Ignored when calcMode="paced".

keySplines#

The easing curves to use for spline pacing.

  • A semicolon-separated list of sets of four (whitespace-separated or comma-separated) numbers between 0 and 1, representing control points for a cubic Bézier curve from (0,0) to (1,1).

  • The four numbers in each set are the same as used in the CSS cubic-bezier() function, and can be generated from many tools, except that CSS allows y values outside 0 and 1 (to create bounce effects).

  • The number of spline-sets in the list must be one fewer than the number of entries in the values and keyTimes lists.

  • Only applies if calcMode="spline" and if keyTimes is specified.

  • Default is 0 0 1 1 for all sets in the list, which is the same as linear interpolation.

Setting additive effects#
additive#

Whether the impact of this animation adds to changes caused by other animations of the same attribute on the same target element.

  • Options are sum (meaning, it is additive) or replace (the default).

  • Only applies for additive attributes.

  • For replace, the actual effect depends on whether or not this animation sets a from value (or a values) list: to and by animations without from are always calculated relative to other animations in effect on the element.

accumulate#

Whether subsequent repeats of this animation add to each other.

  • Options are sum (meaning, it is additive) or none (the default).

  • Only applies for additive attributes.

  • Makes the most sense when used with by animations, but also applies to values and from/to animations; the net change for each value in the first iteration of the animation is converted into relative amounts for subsequent repeats.

  • Ignored for to animations without from.

The elements and their unique attributes are listed below:

<animate>#

Animates an attribute or style property, with continuous interpolation if possible (and depending on calcMode). All of the above attributes apply.

<set>#

Applies a discrete change, setting a single value for the duration of the animation. The value is set by to; from, by, and values are ignored, as are pacing and additive attributes.

<animateTransform>#

Animates a transform-related attribute (transform, patternTransform, or gradientTransform) by interpolating the parameters to a particular transformation function.

The attributeName attribute is still required, it does not default to transform.

type#

Which transformation function to animate; the animation values will be treated as parameters to this function.

  • One of translate, rotate, scale, skewX, or skewY.

  • Should default to translate, but this is not well supported.

<animateMotion>#

Applies an additional transformation to this element (separate from any transform transformation), either defined as a series of positions in the coordinate system or by an SVG path shape.

The origin of the transformed element’s coordinate system will be translated to match the specified position values or the points on the path, after the path is first re-drawn in the local coordinate system.

from, to, by, and values#

Define a motion path as x,y points.

  • Each value requires two lengths, separated by whitespace or a comma.

  • Each length can be a number of pixels or a length with units (but units aren’t well supported).

  • Ignored if this element has a path attribute or a child <mpath> element.

path#

Defines a motion path using SVG path data.

  • The same format as the d attribute of the <path> element.

  • Ignored if this element has a child <mpath> element.

keyPoints#

Relative distances along the path to use as the values for keyTimes and keySplines pacing.

  • A semicolon-spearated list of values between 0 and 1, representing proportions of the path length.

  • Can be used (even with paced calculations) to create motion that only covers part of a path (keyPoints="0;0.5") or that goes to the end of an open path and back (keyPoints="0;1;0").

  • Default is to use the actual points on the path (the end points of each path segment), skipping any move-to commands, or the points in the values list.

rotate#

How to rotate the element after translating it into place.

  • Either one of the keywords auto or auto-reverse, or a number representing an angle in degrees.

  • auto and auto-reverse adjust the rotation so the x-axis of the moving element matches the tangent of the path; for auto-reverse, the element is rotated 180° so that the x-axis points backwards along the path.

  • A number applies a fixed-degree rotation, regardless of path position.

  • Default 0 (meaning no rotation).

<mpath>#

A motion path for a parent <animateMotion>, specified as a cross-reference to a <path> element.

The referenced path.

Obsolete and Deprecated Elements#

The following elements from SVG 1 were either never supported in web browsers, or have been explicitly deprecated. The HTML and XML parsers should still recognize them as SVG elements, and there is limited support for SVG Fonts in some browsers, but otherwise they should be avoided.

<font>, <glyph>, <hkern>, <missing-glyph>, and <vkern>#

These elements were used to define SVG Fonts.

<font-face>, <font-face-format>, <font-face-name>, <font-face-src>, and <font-face-uri>#

These elements provided XML equivalents to the CSS @font-face rule. They could be used with SVG Fonts, to describe the characteristics of the font itself, but they could also be used to describe the characteristics of an external font file, for software without CSS support.

<altGlyph>#

Like a <tspan>, this element was a container for text content within a <text> element, and had similar text positioning attributes. However, it also had attributes that specified the particular glyphs (letterforms) to be used to render that text, instead of the default glyphs for those characters from the font.

An <altGlyph> could be used with SVG Fonts, but did not have to be: many other font formats have alternative glyphs for characters. Similar functionality (for OpenType fonts, anyway) is provided by the newer CSS font-feature-settings property.

<altGlyphDef>, <altGlyphItem> and <glyphRef>#

These elements would be used in combination with <altGlyph>, allowing you to specify a sequence of alternative glyphs, or set of alternatives for different fallback fonts. The alternative glyphs would only be used if all of the glyphs in a sequence could be successfully loaded.

<tref>#

Like a <use> element for text content, a <tref> would be a child of <text> and would reference another element. The referenced element’s text content would be then rendered as if the <tref> was a <tspan> containing that text.

<color-profile>#

Defined an ICC color profile that could be referenced in other color-related properties. As described (briefly) in Chapter 12 in the book, similar functionality is proposed in CSS Color Level 4, using an @color-profile rule.

<cursor>#

Defined a custom image file for use with the CSS cursor property, instead of one of the keyword cursors. This element’s functionality (linking to an image file, and specifying a reference point within it) has now been completely integrated in the style property, so it is obsolete.