SVG: Specifying Styles

By Xah Lee. Date: . Last updated: .

SVG style sheet is basically the same as CSS, and share many of the same attribute name and semantics with 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:

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: Basic Shape Styles

SVG: Basic Shape Styles

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.