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?>target: Identifies the application or processor intended to handle the instruction (for example,xml-stylesheet). The target name cannot contain spaces and cannot begin with the word “xml” unless specifically defined by the W3C XML specifications.data: The parameters or instructions provided to the processor, typically structured as key-value pseudo-attributes.
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:
href(required): Specifies the URI of the external stylesheet file or an internal fragment identifier.type(required): Specifies the MIME type of the stylesheet language, commonly"text/css".media(optional): Defines the media query/target medium (e.g.,"screen","print").title(optional): Assigns a title to the stylesheet to define alternate or preferred style sets.alternate(optional): Set to"yes"or"no"to indicate if the stylesheet is an alternative rather than persistent.
Placement and Rules
Processing instructions must adhere to standard XML structure rules:
- 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. - Whitespace: There must be at least one whitespace character between the target name and the first pseudo-attribute.
- Quotes: Values for pseudo-attributes must be
enclosed in single (
') or double (") quotation marks. - 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>