SVG: Specifying Styles

By Xah Lee. Date: . Last updated: .

SVG style sheet is basically the same as CSS.

(If you don't know CSS, see CSS Basics.)

Some of the SVG style attribute names are different from CSS.

There are 4 ways to specify SVG style:

  1. SVG Element Attribute. For example, <line … stroke="black" />
  2. Inline CSS as style attribute in the tag. For example, <line style="stroke:black;…" …/>
  3. Internal CSS. (declared in file header)
  4. external CSS. A link to style file.

Here's explanation of each.

1, SVG Element Attribute

<line x1="0" y1="0" x2="50" y2="10" stroke="black" />

The stroke is a style attribute for the SVG line element.

2, Inline CSS (style attribute)

<!-- inline styling -->
<line x1="0" y1="0" x2="50" y2="10" style="stroke:black" />

The style="…" is general way to style each SVG element.

3, Internal CSS (in File Header)

Here's a example of internal style sheet:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="12cm" height="3cm" viewBox="0 0 1200 300" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <style type="text/css">
    <![CDATA[
      #x123 { fill: blue }
      path { fill-opacity: .5 }
      .y567 { stroke-linecap: round }
    ]]>
  </style>
</svg>

Note: because it's XML file, so you must enclose it with <![CDATA[…]]>.

4, External CSS (Link to Style File)

Here's example with external style sheet. Basically a link to style file:

<!-- external style sheet-->
<?xml version="1.0" standalone="no"?>
<?xml-stylesheet href="my_style.css" type="text/css"?>
<!DOCTYPE svg …>
<svg …>
…
</svg>

SVG: Shape Styles

SVG: Shape Styles

SVG tutorial

  1. SVG Basics
  2. Path
  3. Path Elliptical Arc
  4. Circle Arc
  5. Specifying Styles
  6. Shape Styles
  7. Viewport
  8. viewBox
  9. ViewBox Unit Size
  10. Coordinate Transformation
  11. Text Element
  12. Font Size
  13. Structure Elements
  14. Scripting SVG
  15. SVG Clock
  16. Animation

Canvas Intro

  1. Canvas vs SVG
  2. Canvas intro
  3. Demo: Halma
  4. Demo: Raycaster
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials