SVG Processing Instruction Syntax Explained

Scalable Vector Graphics (SVG) files are XML-based documents that can include processing instructions to pass specific directives to the rendering engine or XML parser. This guide breaks down the syntax of SVG processing instructions, details the most common application—linking external CSS stylesheets using the xml-stylesheet instruction—and outlines the essential formatting rules for valid SVG documents.

General Processing Instruction Syntax

An XML processing instruction (PI) in an SVG file begins with the delimiter <? and ends with ?>. It consists of a target name followed immediately by optional instruction data or pseudo-attributes.

The general syntax format is:

<?target data?>

The xml-stylesheet Processing Instruction

The most frequent processing instruction used in SVG is xml-stylesheet, which links external CSS files or applies styling rules directly before the SVG DOM is constructed.

Syntax:

<?xml-stylesheet href="styles.css" type="text/css"?>

Supported Pseudo-Attributes:


Placement and Rules

Processing instructions must adhere to standard XML structure rules:

  1. Prolog Placement: Processing instructions must appear in the XML prolog, situated after the XML declaration (<?xml version="1.0"?>) and before the root <svg> element.
  2. Whitespace: There must be at least one whitespace character between the target name and the first pseudo-attribute.
  3. Quotes: Values for pseudo-attributes must be enclosed in single (') or double (") quotation marks.
  4. No Direct Nesting: Processing instructions cannot be placed inside individual SVG element tags, though they can appear between element nodes inside the document tree if needed by specific parsers.

Complete Example in an SVG File

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="theme.css" type="text/css"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  <circle cx="50" cy="50" r="40" class="primary-circle" />
</svg>