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. Specifying Styles
  5. Shape Styles
  6. Viewport
  7. viewBox
  8. Coordinate Transformation
  9. Text Element
  10. Font Size
  11. Structure Elements
  12. Scripting SVG
  13. SVG Clock
  14. Animation
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog