SVG Essentials/Introduction to Stylesheets

From WikiContent

Jump to: navigation, search
SVG Essentials

As mentioned in Chapter 4, some attributes of SVG elements control the element's geometry. An example of one such attribute would be the cx (center x) attribute of a <circle>. Other attributes, such as fill, control the element's presentation. Stylesheets provide a way for you to separate the presentation from the geometric structure; this lets you control the visual display of many different SVG elements (and even documents) by changing one stylesheet referenced by all the documents.


Anatomy of a Style

A style is a specification of a visual property for an element and the value that you would like that property to have. The property name and the value are separated by a colon. For example, to say that you want the stroke color for some element to be blue, the appropriate style specifier would be stroke: blue.

To specify multiple properties in a style, you separate the specifiers with semicolons. The following style specifier sets the stroke color to red, the stroke width to three pixels, and the fill color to a light blue. The last property-value pair is followed by a semicolon. This is not necessary, but is done to give the style a more consistent look.

stroke: red; stroke-width: 3px; fill: #ccccff;

Style Selectors

Once you have determined the visual properties you'd like, you must select the element or elements to which they apply. The simplest way to apply a style specification to a single element is to make that specification the value of a style attribute. So, if you want the preceding specification to apply to a particular <circle> in your document, you write:

<circle cx="50" cy="40" r="12"
    style="stroke: red; stroke-width: 3px; fill: #ccccff;"/>

Internal Stylesheets

If you want the style specification to apply to all <circle> elements in a single document, add an internal stylesheet. A style sheet consists of selectors (the names of the elements you want to affect) and the style specifications for those selectors. The style specification is enclosed in curly braces. The following applies styles to <circle> and <rect> elements:

<style type="text/css"><![CDATA[
      circle {
        stroke: red; stroke-width: 3px;
        fill: #ccccff;
      rect { fill: gray; stroke: black; }

When you put a <style> element into an SVG document, you should enclose its contents within <![[CDATA[ and ]]>. This notation tells XML parsers that the contents are pure character data and should not, under any circumstances, be treated as information for XML to parse.

Because this stylesheet is within a document, it applies to that document alone. If you have many documents, all of whose circles and rectangles appear as specified in the preceding example, take the specifiers, without any of the tags, and put them into a separate myStyle.css file. In each SVG document, insert the following processing instruction:

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

Then, at a later point, if you decide that all rectangles should be filled with a light green and outlined in dark green, you can simply change the specification in myStyle.css to read:

    rect {fill: #ccffcc; stroke: #006600; }

and all your documents, once redisplayed, will have green rectangles instead of gray rectangles.

Style Selector Classes

The preceding stylesheet affects all <rect> and <circle> elements. Let's say, though, that you want only some circles in your documents to be styled. Write your stylesheet with a class specifier as follows, where the dot after circle indicates that the following identifier is a class name:

      circle.special {
        stroke: red; stroke-width: 3px;
        fill: #ccccff;

If, in your SVG document, you had the following elements, the first circle would show up as the default (black fill, no stroke), and the second would take on the style attributes as its class name matches the class identifier in the stylesheet.

<circle cx="40" cy="40" r="20"/>
<circle cx="60" cy="20" r="10" class="special"/>

It is possible to specify a generic class that can apply to any element. Presume that several different graphic objects serve as warning symbols. You would like them to have a yellow fill and a red border. You could write this selector, which consists only of a class name and its style specifier:

    .warning { fill: yellow; stroke: red; }

This generic class may now be applied to any SVG element. In the following example, both the rectangle and triangle will have yellow interiors and red outlines.

<rect class="warning" x="5" y="10" width="20" height="30"/>
<polygon class="warning" points="40 40, 40 60, 60 50"/>

The class attribute may contain the names of several classes; their combined properties will be applied to the element in question. We will add a generic class named seeThrough for translucency to the previous example, and then apply both classes to the polygon.

<svg width="100" height="100" viewBox="0 0 100 100">
    <style type="text/css"><![CDATA[
        .warning { fill: yellow; stroke: red; }
        .seeThrough { fill-opacity: 0.25; stroke-opacity: 0.5; }
    <rect class="warning" x="5" y="10" width="20" height="30"/>
    <polygon class="warning seeThrough" points="40 40, 40 60, 60 50"/>

Using CSS with SVG

The question then becomes: which attributes in SVG elements can also be specified in a stylesheet? Table B-1 is a list of the properties you may use in a stylesheet, the valid values (with default value shown in boldface where appropriate), and the elements to which they may be applied. It is a modified version of the property index from the SVG specification at[1]

Table B-1. CSS property table for SVG

Name Values Applies to
alignment-baseline auto | baseline | before-edge | text-before-edge | middle | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical <tspan>, <tref>, <altGlyph>, <textPath>
baseline-shift baseline | sub | super | percentage | length <tspan>, <tref>, <altGlyph>, <textPath> elements
clip shape | auto Elements which establish a new viewport, <pattern> elements and <marker> elements
clip-path uri Container elements and graphics elements
clip-rule nonzero | evenodd | class=noxref Graphics elements within a <clipPath> element
color color Elements to which properties fill, stroke, stop-color, flood-color, lighting-color apply
color-interpolation auto | sRGB | linearRGB Container elements, graphics elements and <animateColor>
color-interpolation-filters auto | sRGB | linearRGB Filter primitives
color-profile auto | sRGB | name | uri <image> elements that refer to raster images
color-rendering auto | optimizeSpeed | optimizeQuality Container elements, graphics elements and <animateColor>
cursor uri | auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help Container elements and graphics elements
direction ltr | rtl <text>, <tspan>, <tref> and <textPath> elements
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 <svg>, <g>, <switch>, <a>, <foreignObject>, graphics elements (including the <text> element) and text sub-elements (i.e., <tspan>, <tref>, <altGlyph>, <textPath>)
dominant-baseline auto | use-script | no-change | reset-size | alphabetic | hanging | ideographic | mathematical | central | middle | text-after-edge | text-before-edge | text-top | text-bottom Text content elements
enable-background accumulate | new [ x'y'width'height ] Container elements
fill paint (default black) Shapes and text content elements
fill-opacity opacity-value (default 1) Shapes and text content elements
fill-rule nonzero | evenodd Shapes and text content elements
filter uri | none Container elements and graphics elements
flood-color currentColor | color specifier (default black) <feFlood> elements
flood-opacity alphavalue (default 1) <feFlood> elements
font font-style, font-variant, font-weight, font-sizeline-height, font-family | caption | icon | menu | message-box | small-caption | status-bar Text content elements
font-family series of family-name or generic-family Text content elements
font-size absolute-size | relative-size | length | percentage Text content elements
font-size-adjust number | none Text content elements
font-stretch normal | wider | narrower | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded Text content elements
font-style normal | italic | oblique Text content elements
font-variant normal | small-caps Text content elements
font-weight normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 Text content elements
glyph-orientation-horizontal angle (default 0deg) Text content elements
glyph-orientation-vertical auto | angle Text content elements
image-rendering auto | optimizeSpeed | optimizeQuality images
kerning auto | length Text content elements
letter-spacing normal | length Text content elements
lighting-color currentColor | color specification (default white) <feDiffuseLighting> and <feSpecularLighting> elements
marker, marker-end, marker-mid, marker-start none | uri <path>, <line>, <polyline> and <polygon> elements
mask uri | none Container elements and graphics elements
opacity alphavalue (default 1) Container elements and graphics elements
overflow visible | hidden | scroll | auto Elements which establish a new viewport, <pattern> elements and <marker> elements
pointer-events visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | none Graphics elements
shape-rendering auto | optimizeSpeed | crispEdges | geometricPrecision Shapes
stop-color currentColor | color specification (default black) <stop> elements
stop-opacity alphavalue (default 1) <stop> elements
stroke paint Shapes and text content elements
stroke-dasharray none | dasharray Shapes and text content elements
stroke-dashoffset dashoffset (default 0) Shapes and text content elements
stroke-linecap butt | round | square Shapes and text content elements
stroke-linejoin miter | round | bevel Shapes and text content elements
stroke-miterlimit miterlimit (default 4) Shapes and text content elements
stroke-opacity opacity-value (default 1) Shapes and text content elements
stroke-width width (default 1) Shapes and text content elements
text-anchor start | middle | end Text content elements
text-decoration none | underline | overline | line-through | blink Text content elements
text-rendering auto | optimizeSpeed | optimizeLegibility | geometricPrecision <text> elements
unicode-bidi normal | embed | bidi-override Text content elements
visibility visible | hidden | collapse Graphics elements (including the <text> element) and text sub-elements (i.e., <tspan>, <tref>, <altGlyph>, <textPath> and <a>)
word-spacing normal | length Text content elements
writing-mode lr-tb | rl-tb | tb-rl | lr | rl | tb <text> elements


  1. Copyright (C) 2001 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University) All Rights Reserved.
Personal tools