previous next contents elements attributes properties index

04 September 2001

# 6 Styling

## Contents

## 6.1 SVG's styling properties

SVG uses styling properties to describe many of its document parameters. Styling properties define how the graphics elements in the SVG content are to be rendered. SVG uses styling properties for the following:

- Parameters which are clearly visual in nature and thus lend themselves to styling. Examples include all attributes that define how an object is "painted," such as fill and stroke colors, linewidths and dash styles.
- Parameters having to do with text styling such as 'font-family' and 'font-size'.
- Parameters which impact the way that graphical elements are rendered, such as specifying clipping paths, masks, arrowheads, markers and filter effects.

SVG shares many of its styling properties with CSS [CSS2] and XSL [XSL]. Except for any additional SVG-specific rules explicitly mentioned in this specification, the normative definition of properties that are shared with CSS and XSL is the definition of the property from the CSS2 specification [CSS2].

The following properties are shared between CSS2 and SVG. Most of these properties are also defined in XSL:

- Font properties:
  - 'font'
  - 'font-family'
  - 'font-size'
  - 'font-size-adjust'
  - 'font-stretch'
  - 'font-style'
  - 'font-variant'
  - 'font-weight'
- Text properties:
  - 'direction'
  - 'letter-spacing'
  - 'text-decoration'
  - 'unicode-bidi'
  - 'word-spacing'
- Other properties for visual media:
  - 'clip' (Only applicable to outermost 'svg')
  - 'color' is used to provide a potential indirect value (currentColor) for the 'fill', 'stroke', 'stop-color', 'flood-color', 'lighting-color' properties. (The SVG properties which support color allow a color specification which is extended from CSS2 to accommodate color definitions in arbitrary color spaces. See Color profile descriptions.
  - 'cursor'
  - 'display'
  - 'overflow' (Only applicable to elements which establish a new viewport)
  - 'visibility'

The following SVG properties are not defined in [CSS2]. The complete normative definitions for these properties are found in this specification:

- Clipping, Masking and Compositing properties:
  - 'clip-path'
  - 'clip-rule'
  - 'mask'
  - 'opacity'
- Filter Effects properties:
  - 'enable-background'
  - 'filter'
  - 'flood-color'
  - 'flood-opacity'
  - 'lighting-color'
- Gradient properties:
  - 'stop-color'
  - 'stop-opacity'
- Interactivity properties:
  - 'pointer-events'
- Color and Painting properties:
  - 'color-interpolation'
  - 'color-interpolation-filters'
  - 'color-profile'
  - 'color-rendering'
  - 'fill'
  - 'fill-opacity'
  - 'fill-rule'
  - 'image-rendering'
  - 'marker'
  - 'marker-end'
  - 'marker-mid'
  - 'marker-start'
  - 'shape-rendering'
  - 'stroke'
  - 'stroke-dasharray'
  - 'stroke-dashoffset'
  - 'stroke-linecap'
  - 'stroke-linejoin'
  - 'stroke-miterlimit'
  - 'stroke-opacity'
  - 'stroke-width'
  - 'text-rendering'
- Text properties:
  - 'alignment-baseline'
  - 'baseline-shift'
  - 'dominant-baseline'
  - 'glyph-orientation-horizontal'
  - 'glyph-orientation-vertical'
  - 'kerning'
  - 'text-anchor'
  - 'writing-mode'

A table that lists and summarizes the styling properties can be found in the Property Index.

## 6.2 Usage scenarios for styling

SVG has many usage scenarios, each with different needs. Here are three common usage scenarios:

1. SVG content used as an exchange format (style sheet language-independent):

   In some usage scenarios, reliable interoperability of SVG content across software tools is the main goal. Since support for a particular style sheet language is not guaranteed across all implementations, it is a requirement that SVG content can be fully specified without the use of a style sheet language.

2. SVG content generated as the output from XSLT [XSLT]:

   XSLT offers the ability to take a stream of arbitrary XML content as input, apply potentially complex transformations, and then generate SVG content as output. XSLT can be used to transform XML data extracted from databases into an SVG graphical representation of that data. It is a requirement that fully specified SVG content can be generated from XSLT.

3. SVG content styled with CSS [CSS2]:

   CSS is a widely implemented declarative language for assigning styling properties to XML content, including SVG. It represents a combination of features, simplicity and compactness that makes it very suitable for many applications of SVG. It is a requirement that CSS styling can be applied to SVG content.

## 6.3 Alternative ways to specify styling properties

Styling properties can be assigned to SVG elements in the following two ways:

- Presentation attributes

  Styling properties can be assigned using SVG's presentation attributes. For each styling property defined in this specification, there is a corresponding XML presentation attribute available on all relevant SVG elements. Detailed information on the presentation attributes can be found in Specifying properties using the presentation attributes.

  The presentation attributes are style sheet language independent and thus are applicable to usage scenario 1 above (i.e., tool interoperability). Because it is straightforward to assign values to XML attributes from XSLT, the presentation attributes are well-suited to usage scenario 2 above (i.e., SVG generation from XSLT). (See Styling with XSL below.)

  Conforming SVG Interpreters and Conforming SVG Viewers are required to support SVG's presentation attributes.

- CSS

  To support usage scenario 3 above, SVG content can be styled with CSS. For more information, see Styling with CSS.

  Conforming SVG Interpreters and Conforming SVG Viewers that support CSS styling of generic (i.e., text-based) XML content are required to support CSS styling of SVG content.

## 6.4 Specifying properties using the presentation attributes

For each styling property defined in this specification (see Property Index), there is a corresponding XML attribute (the presentation attribute) with the same name that is available on all relevant SVG elements. For example, SVG has a 'fill' property that defines how to paint the interior of a shape. There is a corresponding presentation attribute with the same name (i.e., fill) that can be used to specify a value for the 'fill' property on a given element.

The following example shows how the 'fill' and 'stroke' properties can be assigned to a rectangle using the fill and stroke presentation attributes. The rectangle will be filled with red and outlined with blue:

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
      "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg width="10cm" height="5cm" viewBox="0 0 1000 500"
         xmlns="http://www.w3.org/2000/svg">
      <rect x="200" y="100" width="600" height="300"
            fill="red" stroke="blue" stroke-width="3"/>
    </svg>

View this example as SVG (SVG-enabled browsers only)

The presentation attributes offer the following advantages:

- Broad support. All versions of Conforming SVG Interpreters and Conforming SVG Viewers are required to support the presentation attributes.
- Simplicity. Styling properties can be attached to elements by simply providing a value for the presentation attribute on the proper elements.
- Restyling. SVG content that uses the presentation attributes is highly compatible with downstream processing using XSLT [XSLT] or supplemental styling by adding CSS style rules to override some of the presentation attributes.
- Convenient generation using XSLT [XSLT]. In some cases, XSLT can be used to generate fully styled SVG content. The presentation attributes are compatible with convenient generation of SVG from XSLT.

In some situations, SVG content that uses the presentation attributes has potential limitations versus SVG content that is styled with a style sheet language such as CSS (see Styling with CSS). In other situations, such as when an XSLT style sheet generates SVG content from semantically rich XML source files, the limitations below may not apply. Depending on the situation, some of the following potential limitations may or may not apply to the presentation attributes:

- Styling attached to content. The presentation attributes are attached directly to particular elements, thereby diminishing potential advantages that comes from abstracting styling from content, such as the ability to restyle documents for different uses and environments.
- Flattened data model. In and of themselves, the presentation attributes do not offer the higher level abstractions that you get with a styling system, such as the ability to define named collections of properties which are applied to particular categories of elements. The result is that, in many cases, important higher level semantic information can be lost, potentially making document reuse and restyling more difficult.
- Potential increase in file size. Many types of graphics use similar styling properties across multiple elements. For example, a company organization chart might assign one collection of styling properties to the boxes around temporary workers (e.g., dashed outlines, red fill), and a different collection of styling properties to permanent workers (e.g., solid outlines, blue fill). Styling systems such as CSS allow collections of properties to be defined once in a file. With the styling attributes, it might be necessary to specify presentation attributes on each different element.
- Potential difficulty when embedded into a CSS-styled parent document. When SVG content is embedded in other XML, and the desire is to style all aspects of the compound document with CSS, use of the presentation attributes might introduce complexity and difficulty. In this case, it is sometimes easier if the SVG content does not use the presentation attributes and instead is styled using CSS facilities.

For user agents that support CSS, the presentation attributes must be translated to corresponding CSS style rules according to rules described in section 6.4.4 of the CSS2 specification, Precedence of non-CSS presentational hints, with the additional clarification that the presentation attributes are conceptually inserted into a new author style sheet which is the first in the author style sheet collection. The presentation attributes thus will participate in the CSS2 cascade as if they were replaced by corresponding CSS style rules placed at the start of the author style sheet with a specificity of zero. In general, this means that the presentation attributes have lower priority than other CSS style rules specified in author style sheets or style attributes.

User agents that do not support CSS must ignore any CSS style rules defined in CSS style sheets and style attributes. In this case, the CSS cascade does not apply. (Inheritance of properties, however, does apply. See Property inheritance.)

An !important declaration within a presentation attribute definition is an error.

Animation of presentation attributes is equivalent to animating the corresponding property. Thus, the same effect occurs from animating the presentation attribute with attributeType="XML" as occurs with animating the corresponding property with attributeType="CSS".

## 6.5 Entity definitions for the presentation attributes

The following entities are defined in the DTD for all of the presentation attributes in SVG:

    <!-- The following presentation attributes have to do with specifying color. -->
    <!ENTITY % PresentationAttributes-Color
      "color %Color; #IMPLIED
       color-interpolation (auto | sRGB | linearRGB | inherit) #IMPLIED
       color-rendering (auto | optimizeSpeed | optimizeQuality | inherit) #IMPLIED " >

    <!-- The following presentation attributes apply to container elements. -->
    <!ENTITY % PresentationAttributes-Containers
      "enable-background %EnableBackgroundValue; #IMPLIED " >

    <!-- The following presentation attributes apply to 'feFlood' elements. -->
    <!ENTITY % PresentationAttributes-feFlood
      "flood-color %SVGColor; #IMPLIED
       flood-opacity %OpacityValue; #IMPLIED " >

    <!-- The following presentation attributes apply to filling and stroking operations. -->
    <!ENTITY % PresentationAttributes-FillStroke
      "fill %Paint; #IMPLIED
       fill-opacity %OpacityValue; #IMPLIED
       fill-rule %ClipFillRule; #IMPLIED
       stroke %Paint; #IMPLIED
       stroke-dasharray %StrokeDashArrayValue; #IMPLIED
       stroke-dashoffset %StrokeDashOffsetValue; #IMPLIED
       stroke-linecap (butt | round | square | inherit) #IMPLIED
       stroke-linejoin (miter | round | bevel | inherit) #IMPLIED
       stroke-miterlimit %StrokeMiterLimitValue; #IMPLIED
       stroke-opacity %OpacityValue; #IMPLIED
       stroke-width %StrokeWidthValue; #IMPLIED " >

    <!-- The following presentation attributes apply to filter primitives. -->
    <!ENTITY % PresentationAttributes-FilterPrimitives
      "color-interpolation-filters (auto | sRGB | linearRGB | inherit) #IMPLIED " >

    <!-- The following presentation attributes have to do with selecting a font to use. -->
    <!ENTITY % PresentationAttributes-FontSpecification
      "font-family %FontFamilyValue; #IMPLIED
       font-size %FontSizeValue; #IMPLIED
       font-size-adjust %FontSizeAdjustValue; #IMPLIED
       font-stretch (normal | wider | narrower | ultra-condensed | extra-condensed |
                     condensed | semi-condensed | semi-expanded | expanded |
                     extra-expanded | ultra-expanded | inherit) #IMPLIED
       font-style (normal | italic | oblique | inherit) #IMPLIED
       font-variant (normal | small-caps | inherit) #IMPLIED
       font-weight (normal | bold | bolder | lighter | 100 | 200 | 300 |
                   400 | 500 | 600 | 700 | 800 | 900 | inherit) #IMPLIED " >

    <!-- The following presentation attributes apply to gradient 'stop' elements. -->
    <!ENTITY % PresentationAttributes-Gradients
      "stop-color %SVGColor; #IMPLIED
       stop-opacity %OpacityValue; #IMPLIED " >

    <!-- The following presentation attributes apply to graphics elements. -->
    <!ENTITY % PresentationAttributes-Graphics
      "clip-path %ClipPathValue; #IMPLIED
       clip-rule %ClipFillRule; #IMPLIED
       cursor %CursorValue; #IMPLIED
       display (inline | block | list-item | run-in | compact | marker |
                table | inline-table | table-row-group | table-header-group |
                table-footer-group | table-row | table-column-group | table-column |
                table-cell | table-caption | none | inherit) #IMPLIED
       filter %FilterValue; #IMPLIED
       image-rendering (auto | optimizeSpeed | optimizeQuality | inherit) #IMPLIED
       mask %MaskValue; #IMPLIED
       opacity %OpacityValue; #IMPLIED
       pointer-events (visiblePainted | visibleFill | visibleStroke | visible |
                       painted | fill | stroke | all | none | inherit) #IMPLIED
       shape-rendering (auto | optimizeSpeed | crispEdges | geometricPrecision | inherit) #IMPLIED
       text-rendering (auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit) #IMPLIED
       visibility (visible | hidden | inherit) #IMPLIED " >

    <!-- The following presentation attributes apply to 'image' elements. -->
    <!ENTITY % PresentationAttributes-Images
      "color-profile CDATA #IMPLIED " >

    <!--The following presentation attributes apply to 'feDiffuseLighting' and 'feSpecularLighting' elements. -->
    <!ENTITY % PresentationAttributes-LightingEffects
      "lighting-color %SVGColor; #IMPLIED " >

    <!-- The following presentation attributes apply to marker operations. -->
    <!ENTITY % PresentationAttributes-Markers
      "marker-start %MarkerValue; #IMPLIED
       marker-mid %MarkerValue; #IMPLIED
       marker-end %MarkerValue; #IMPLIED " >

    <!-- The following presentation attributes apply to text content elements. -->
    <!ENTITY % PresentationAttributes-TextContentElements
      "alignment-baseline (baseline | top | before-edge | text-top | text-before-edge |
                            middle | bottom | after-edge | text-bottom | text-after-edge |
                            ideographic | lower | hanging | mathematical | inherit) #IMPLIED
       baseline-shift %BaselineShiftValue; #IMPLIED
       direction (ltr | rtl | inherit) #IMPLIED
       dominant-baseline (auto | autosense-script | no-change | reset|
                          ideographic | lower | hanging | mathematical | inherit ) #IMPLIED
       glyph-orientation-horizontal %GlyphOrientationHorizontalValue; #IMPLIED
       glyph-orientation-vertical %GlyphOrientationVerticalValue; #IMPLIED
       kerning %KerningValue; #IMPLIED
       letter-spacing %SpacingValue; #IMPLIED
       text-anchor (start | middle | end | inherit) #IMPLIED
       text-decoration %TextDecorationValue; #IMPLIED
       unicode-bidi (normal | embed | bidi-override | inherit) #IMPLIED
       word-spacing %SpacingValue; #IMPLIED " >

    <!-- The following presentation attributes apply to 'text' elements. -->
    <!ENTITY % PresentationAttributes-TextElements
      "writing-mode (lr-tb | rl-tb | tb-rl | lr | rl | tb | inherit) #IMPLIED " >

    <!-- The following presentation attributes apply to elements that establish viewports. -->
    <!ENTITY % PresentationAttributes-Viewports
      "clip %ClipValue; #IMPLIED
       overflow (visible | hidden | scroll | auto | inherit) #IMPLIED " >

    <!--The following represents the complete list of presentation attributes. -->
    <!ENTITY % PresentationAttributes-All
      "%PresentationAttributes-Color;
       %PresentationAttributes-Containers;
       %PresentationAttributes-feFlood;
       %PresentationAttributes-FillStroke;
       %PresentationAttributes-FilterPrimitives;
       %PresentationAttributes-FontSpecification;
       %PresentationAttributes-Gradients;
       %PresentationAttributes-Graphics;
       %PresentationAttributes-Images;
       %PresentationAttributes-LightingEffects;
       %PresentationAttributes-Markers;
       %PresentationAttributes-TextContentElements;
       %PresentationAttributes-TextElements;
       %PresentationAttributes-Viewports;" >

## 6.6 Styling with XSL

XSL style sheets (see [XSLT]) define how to transform XML content into something else, usually other XML. When XSLT is used in conjunction with SVG, sometimes SVG content will serve as both input and output for XSL style sheets. Other times, XSL style sheets will take non-SVG content as input and generate SVG content as output.

The following example uses an external XSL style sheet to transform SVG content into modified SVG content (see Referencing external style sheets). The style sheet sets the 'fill' and 'stroke' properties on all rectangles to red and blue, respectively:

    mystyle.xsl

    <?xml version="1.0" standalone="no"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

      <!-- Add DOCTYPE -->
      <xsl:template match="/">
        <xsl:text disable-output-escaping="yes"><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
          "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    </xsl:text>
        <xsl:apply-templates/>
      </xsl:template>

      <!-- Add styling to all 'rect' elements -->
      <xsl:template match="rect">
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:attribute name="fill">red</xsl:attribute>
          <xsl:attribute name="stroke">blue</xsl:attribute>
          <xsl:attribute name="stroke-width">3</xsl:attribute>
        </xsl:copy>
      </xsl:template>

      <!-- default is to copy input element -->
      <xsl:template match="*|@*|text()">
        <xsl:copy>
          <xsl:apply-templates select="*|@*|text()"/>
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>

    SVG file to be transformed by mystyle.xsl

    <?xml version="1.0" standalone="no"?>
    <svg width="10cm" height="5cm"
         xmlns="http://www.w3.org/2000/svg">
      <rect x="2cm" y="1cm" width="6cm" height="3cm"/>
    </svg>

    SVG content after applying mystyle.xsl

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
          "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg width="10cm" height="5cm"
         xmlns="http://www.w3.org/2000/svg">
      <rect x="2cm" y="1cm" width="6cm" height="3cm" fill="red" stroke="blue" stroke-width="3"/>
    </svg>

## 6.7 Styling with CSS

SVG implementations that support CSS are required to support the following:

- External CSS style sheets referenced from the current document (see Referencing external style sheets)
- Internal CSS style sheets (i.e., style sheets embedded within the current document, such as within an SVG 'style' element)
- Inline style (i.e., CSS property declarations within a style attribute on a particular SVG element)

The following example shows the use of an external CSS style sheet to set the 'fill' and 'stroke' properties on all rectangles to red and blue, respectively:

    mystyle.css

    rect {
      fill: red;
      stroke: blue;
      stroke-width: 3
    }

    SVG file referencing mystyle.css

    <?xml version="1.0" standalone="no"?>
    <?xml-stylesheet href="mystyle.css" type="text/css"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
      "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg width="10cm" height="5cm" viewBox="0 0 1000 500"
         xmlns="http://www.w3.org/2000/svg">
      <rect x="200" y="100" width="600" height="300"/>
    </svg>

View this example as SVG (SVG-enabled browsers only)

CSS style sheets can be embedded within SVG content inside of a 'style' element. The following example uses an internal CSS style sheet to achieve the same result as the previous example:

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
      "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg width="10cm" height="5cm" viewBox="0 0 1000 500"
         xmlns="http://www.w3.org/2000/svg">
      <defs>
        <style type="text/css"><![CDATA[
          rect {
            fill: red;
            stroke: blue;
            stroke-width: 3
          }
        ]]></style>
      </defs>
      <rect x="200" y="100" width="600" height="300"/>
    </svg>

View this example as SVG (SVG-enabled browsers only)

Note how the CSS style sheet is placed within a `CDATA` construct (i.e., `<![CDATA[ ... ]]>`). Placing internal CSS style sheets within `CDATA` blocks is sometimes necessary since CSS style sheets can include characters, such as ">", which conflict with XML parsers. Even if a given style sheet does not use characters that conflict with XML parsing, it is highly recommended that internal style sheets be placed inside `CDATA` blocks.

Implementations that support CSS are also required to support CSS inline style. Similar to the style attribute in HTML, CSS inline style can be declared within a style attribute in SVG by specifying a semicolon-separated list of property declarations, where each property declaration has the form "name: value".

The following example shows how the 'fill' and 'stroke' properties can be assigned to a rectangle using the style attribute. Just like the previous example, the rectangle will be filled with red and outlined with blue:

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
      "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg width="10cm" height="5cm" viewBox="0 0 1000 500"
         xmlns="http://www.w3.org/2000/svg">
      <rect x="200" y="100" width="600" height="300"
            style="fill:red; stroke:blue; stroke-width:3"/>
    </svg>

View this example as SVG (SVG-enabled browsers only)

In an SVG user agent that supports CSS style sheets, the following facilities from [CSS2] must be supported:

- CSS2 selectors within style sheets (reference: [Selectors]).
- External CSS style sheets [XML-SS], CSS style sheets within 'style' elements and CSS declaration blocks within style attributes attached to specific SVG elements.
- CSS2 rules for assigning property values, cascading and inheritance.
- @font-face, @media, @import and @charset rules within style sheets.
- CSS2's dynamic pseudo-classes :hover, :active and :focus and pseudo-classes :first-child, :visited, :link and :lang. The remaining CSS2 pseudo-classes, including those having to do with generated content, are not part of the SVG language definition. (Note: an SVG element gains focus when it is selected. See Text selection.)
- For the purposes of aural media, SVG represents a CSS-stylable XML grammar. In user agents that support aural style sheets, CSS aural style properties can be applied as defined in [CSS2]. (See Aural style sheets.)
- CSS style sheets defined within a 'style' element can be immediate character data content of the 'style' element or can be embedded within a `CDATA` block.

SVG defines an @color-profile at-rule [CSS2-ATRULES] for defining color profiles so that ICC color profiles can be applied to CSS-styled SVG content.

Note the following about relative URIs and external CSS style sheets: The CSS2 specification [CSS-URI] says that relative URIs (as defined in [RFC2396]) within style sheets are resolved such that the base URI is that of the style sheet, not that of the referencing document.

## 6.8 Case sensitivity of property names and values

Property declarations via presentation attributes are expressed in XML [XML10], which is case-sensitive. CSS property declarations specified either in CSS style sheets or in a style attribute, on the other hand, are generally case-insensitive with some exceptions (see section 4.1.3 Characters and case in the CSS2 specification).

Because presentation attributes are expressed as XML attributes, presentation attributes are case-sensitive and must match the exact name as listed under "Entity definitions for the presentation attributes", above. When using a presentation attribute to specify a value for the 'fill' property, the presentation attribute must be specified as 'fill' and not 'FILL' or 'Fill'. Keyword values, such as "italic" in `font-style="italic"`, are also case-sensitive and must be specified using the exact case used in the specification which defines the given keyword. For example, the keyword "sRGB" must have lowercase "s" and uppercase "RGB".

Property declarations within CSS style sheets or in a style attribute must only conform to CSS rules, which are generally more lenient with regard to case sensitivity. However, to promote consistency across the different ways for expressing styling properties, it is strongly recommended that authors use the exact property names (usually, lowercase letters and hyphens) as defined in the relevant specification and express all keywords using the same case as is required by presentation attributes and not take advantage of CSS's ability to ignore case.

## 6.9 Facilities from CSS and XSL used by SVG

SVG shares various relevant properties and approaches common to CSS and XSL, plus the semantics of many of the processing rules.

SVG shares the following facilities with CSS and XSL:

- Shared properties. Many of SVG's properties are shared between CSS2, XSL and SVG. (See list of shared properties).
- Syntax rules. (The normative references are [CSS2 syntax and basic data types] and [The grammar of CSS2].)
- Allowable data types. (The normative reference is [CSS2 syntax and basic data types]), with the exception that SVG allows <length> and <angle> values without a unit identifier. See Units.)
- Inheritance rules.
- The color keywords from CSS2 that correspond to the colors used by objects in the user's environment. (The normative reference is [CSS2 system colors].)
- For implementations that support CSS styling of SVG content, then that styling must be compatible with various other rules in CSS. (See Styling with CSS.)

## 6.10 Referencing external style sheets

External style sheets are referenced using the mechanism documented in "Associating Style Sheets with XML documents Version 1.0" [XML-SS].

## 6.11 The 'style' element

The 'style' element allows style sheets to be embedded directly within SVG content. SVG's 'style' element has the same attributes as the corresponding element in HTML (see HTML's 'style' element).

    <!ELEMENT style (#PCDATA) >
    <!ATTLIST style
      %stdAttrs;
      xml:space (preserve) #FIXED "preserve"
      type %ContentType; #REQUIRED
      media %MediaDesc; #IMPLIED
      title %Text; #IMPLIED >

Attribute definitions:

type = content-type
  This attribute specifies the style sheet language of the element's contents. The style sheet language is specified as a content type (e.g., "text/css"), as per [RFC2045]. Authors must supply a value for this attribute; there is no default value.
  Animatable: no.
media = media-descriptors
  This attribute specifies the intended destination medium for style information. It may be a single media descriptor or a comma-separated list. The default value for this attribute is "all". The set of recognized media-descriptors are the list of media types recognized by CSS2 [CSS2 Recognized media types].
  Animatable: no.
title = advisory-title
  (For compatibility with [HTML4]) This attribute specifies an advisory title for the 'style' element.
  Animatable: no.

Attributes defined elsewhere:
  %stdAttrs;, xml:space.

The syntax of style data depends on the style sheet language.

Some style sheet languages might allow a wider variety of rules in the 'style' element than in the style attribute. For example, with CSS, rules can be declared within a 'style' element that cannot be declared within a style attribute.

An example showing the 'style' element is provided above (see example).

## 6.12 The class attribute

Attribute definitions:

class = list
  This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
  Animatable: yes.

The class attribute assigns one or more class names to an element. The element may be said to belong to these classes. A class name may be shared by several element instances. The class attribute has several roles:

- As a style sheet selector (when an author wishes to assign style information to a set of elements).
- For general purpose processing by user agents.

In the following example, the 'text' element is used in conjunction with the class attribute to markup document messages. Messages appear in both English and French versions.

    <!-- English messages -->
    <text class="info" lang="en">Variable declared twice</text>
    <text class="warning" lang="en">Undeclared variable</text>
    <text class="error" lang="en">Bad syntax for variable name</text>

    <!-- French messages -->
    <text class="info" lang="fr">Variable déclarée deux fois</text>
    <text class="warning" lang="fr">Variable indéfinie</text>
    <text class="error" lang="fr">Erreur de syntaxe pour variable</text>

In an SVG user agent that supports CSS styling, the following CSS style rules would tell visual user agents to display informational messages in green, warning messages in yellow, and error messages in red:

    text.info    { color: green }
    text.warning { color: yellow }
    text.error   { color: red }

## 6.13 The style attribute

The style attribute allows per-element style rules to be specified directly on a given element. When CSS styling is used, CSS inline style is specified by including semicolon-separated property declarations of the form "name : value" within the style attribute

Attribute definitions:

style = style
  This attribute specifies style information for the current element. The style attribute specifies style information for a single element. The style sheet language of inline style rules is given by the value of attribute contentStyleType on the 'svg' element. The syntax of style data depends on the style sheet language.
  Animatable: no.

The style attribute may be used to apply a particular style to an individual SVG element. If the style will be reused for several elements, authors should use the 'style' element to regroup that information. For optimal flexibility, authors should define styles in external style sheets.

An example showing the style attribute is provided above (see example).

## 6.14 Specifying the default style sheet language

The contentStyleType attribute on the 'svg' element specifies the default style sheet language for the given document fragment.

contentStyleType = "%ContentType;"
  Identifies the default style sheet language for the given document. This attribute sets the style sheet language for the style attributes that are available on many elements. The value %ContentType; specifies a media type, per [RFC2045]. The default value is "text/css".
  Animatable: no.

## 6.15 Property inheritance

Whether or not the user agent supports CSS, property inheritance in SVG follows the property inheritance rules defined in the CSS2 specification. The normative definition for property inheritance is section 6.2 of the CSS2 specification (see Inheritance).

The definition of each property indicates whether the property can inherit the value of its parent.

In SVG, as in CSS2, most elements inherit computed values [CSS2-COMPUTED]. For cases where something other than computed values are inherited, the property definition will describe the inheritance rules. For specified values [CSS2-SPECIFIED] which are expressed in user units, in pixels (e.g., "20px") or in absolute values [CSS2-COMPUTED], the computed value equals the specified value. For specified values which use certain relative units (i.e., em, ex and percentages), the computed value will have the same units as the value to which it is relative. Thus, if the parent element has a 'font-size' of "10pt" and the current element has a 'font-size' of "120%", then the computed value for 'font-size' on the current element will be "12pt". In cases where the referenced value for relative units is not expressed in any of the standard SVG units (i.e., CSS units or user units), such as when a percentage is used relative to the current viewport or an object bounding box, then the computed value will be in user units.

Note that SVG has some facilities wherein a property which is specified on an ancestor element might effect its descendant element, even if the descendant element has a different assigned value for that property. For example, if a 'clip-path' property is specified on an ancestor element, and the current element has a 'clip-path' of 'none', the ancestor's clipping path still applies to the current element because the semantics of SVG state that the clipping path used on a given element is the intersection of all clipping paths specified on itself and all ancestor elements. The key concept is that property assignment (with possible property inheritance) happens first. After properties values have been assigned to the various elements, then the user agent applies the semantics of each assigned property, which might result in the property assignment of an ancestor element affecting the rendering of its descendants.

## 6.16 The scope/range of styles

The following define the scope/range of style sheets:

Stand-alone SVG document
  There is one parse tree. Style sheets defined anywhere within the SVG document (in style elements or style attributes, or in external style sheets linked with the style sheet processing instruction) apply across the entire SVG document.
Stand-alone SVG document embedded in an HTML or XML document with the 'img', 'object' (HTML) or 'image' (SVG) elements
  There are two completely separate parse trees; one for the referencing document (perhaps HTML or XHTML), and one for the SVG document. Style sheets defined anywhere within the referencing document (in style elements or style attributes, or in external style sheets linked with the style sheet processing instruction) apply across the entire referencing document but have no effect on the referenced SVG document. Style sheets defined anywhere within the referenced SVG document (in style elements or style attributes, or in external style sheets linked with the style sheet processing instruction) apply across the entire SVG document, but do not affect the referencing document (perhaps HTML or XHTML). To get the same styling across both the [X]HTML document and the SVG document, link them both to the same style sheet.
Stand-alone SVG content textually included in an XML document
  There is a single parse tree, using multiple namespaces; one or more subtrees are in the SVG namespace. Style sheets defined anywhere within the XML document (in style elements or style attributes, or in external style sheets linked with the style sheet processing instruction) apply across the entire document, including those parts of it in the SVG namespace. To get different styling for the SVG part, use the style attribute, or put an ID on the 'svg' element and use contextual CSS selectors, or use XSL selectors.

## 6.17 User agent style sheet

The user agent shall maintain a user agent style sheet [CSS2-CASCADE-RULES] for elements in the SVG namespace for visual media [CSS2-VISUAL]. The user agent style sheet below is expressed using CSS syntax; however, user agents are required to support the behavior that corresponds to this default style sheet even if CSS style sheets are not supported in the user agent:

    svg, symbol, image, marker, pattern, foreignObject { overflow: hidden }
    svg { width:attr(width); height:attr(height) }

The first line of the above user agent style sheet will cause the initial clipping path to be established at the bounds of the initial viewport. Furthermore, it will cause new clipping paths to be established at the bounds of the listed elements, all of which are elements that establish a new viewport. (Refer to the description of SVG's use of the 'overflow' property for more information.)

The second line of the above user agent style sheet will cause the width and height attributes on the 'svg' element to be used as the default values for the 'width' and 'height' properties during [CSS2-LAYOUT].

## 6.18 Aural style sheets

For the purposes of aural media, SVG represents a stylable XML grammar. In user agents that support CSS aural style sheets, aural style properties [CSS2-AURAL] can be applied as defined in [CSS2].

Aural style properties can be applied to any SVG element that can contain character data content, including 'desc', 'title, 'tspan'. 'tref'. 'altGlyph' and 'textPath'. On user agents that support aural style sheets, the following [CSS2] properties can be applied:

| 'azimuth' |  | [CSS2-azimuth]
| 'cue' |  | [CSS2-cue]
| 'cue-after' |  | [CSS2-cue-after]
| 'cue-before' |  | [CSS2-cue-before]
| 'elevation' |  | [CSS2-elevation]
| 'pause' |  | [CSS2-pause]
| 'pause-after' |  | [CSS2-pause-after]
| 'pause-before' |  | [CSS2-pause-before]
| 'pitch' |  | [CSS2-pitch]
| 'pitch-range' |  | [CSS2-pitch-range]
| 'play-during' |  | [CSS2-play-during]
| 'richness' |  | [CSS2-richness]
| 'speak' |  | [CSS2-speak]
| 'speak-header' |  | [CSS2-speak-header]
| 'speak-numeral' |  | [CSS2-speak-numeral]
| 'speak-punctuation' |  | [CSS2-speak-punctuation]
| 'speech-rate' |  | [CSS2-speech-rate]
| 'stress' |  | [CSS2-stress]
| 'voice-family' |  | [CSS2-voice-family]
| 'volume' |  | [CSS2-volume]

For user agents that support aural style sheets and also support [DOM2], the user agent is required to support the DOM interfaces defined in [DOM2-CSS] that correspond to aural properties [CSS2-AURAL]. (See Relationship with DOM2 CSS object model.)

## 6.19 DOM interfaces

The following interfaces are defined below: SVGStyleElement.

### Interface SVGStyleElement

The SVGStyleElement interface corresponds to the 'style' element.

IDL Definition

      interface SVGStyleElement : SVGElement {
                 attribute DOMString xmlspace;
                             // raises DOMException on setting
                 attribute DOMString type;
                             // raises DOMException on setting
                 attribute DOMString media;
                             // raises DOMException on setting
                 attribute DOMString title;
                             // raises DOMException on setting
      };

Attributes
  DOMString xmlspace
    Corresponds to attribute xml:space on the given element.
    Exceptions on setting

      DOMException |  | NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.

  DOMString type
    Corresponds to attribute type on the given 'style' element.
    Exceptions on setting

      DOMException |  | NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.

  DOMString media
    Corresponds to attribute media on the given 'style' element.
    Exceptions on setting

      DOMException |  | NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.

  DOMString title
    Corresponds to attribute title on the given 'style' element.
    Exceptions on setting

      DOMException |  | NO_MODIFICATION_ALLOWED_ERR: Raised on an attempt to change the value of a readonly attribute.

previous next contents elements attributes properties index