Styling in SVG

You can change the look of SVG shapes styling them. There are several ways to style the shapes:

  • applying presentation attributes,
  • using style attribute with CSS properties,
  • styling with CSS properties,
  • styling with XSL,

Presentation attributes

It is possible to style SVG with special attributes such as fill, stroke, color, marker, graphics, text, font, etc. In the following example you can see how the circle is stroked and filled.

	<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
		<circle cx="5" cy="5"  r="3" stroke="black" stroke-width="2" fill="red"/>
	</svg>			

Using presentation attributes gives you several advantages:

  • presentation attributes are supported by all SVG viewers,
  • they are simple to use - styling attributes provide a value for presentation attributes on the proper elements,
  • and others.

But when you use presentation properties it is impossible to restyle document for different uses - styling is attached to content. Thus, it is recommended that you use CSS styling.

Styling with CSS

There are three types of CSS styling:

  • External CSS style sheets referenced from the current document
  • Internal CSS style sheets (for example, within <style> element)
  • Inline style (i.e., CSS property declarations within a style attribute on a particular SVG element)

External CSS style sheets

If you have a stylesheet in a separate file, you shoul put it on your web server. Additionally, you need to declarare xml-stylesheet in your SVG file before the <svg> element:

	<?xml-stylesheet type="text/css" href="svg-stylesheet.css" ?>
	<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    	...
	</svg>						
							

Internal CSS style sheets

CSS style sheets can be embedded within SVG content inside of a <style> element:

	<?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="10cm" height="5cm" viewBox="0 0 1000 500" xmlns="http://www.w3.org/2000/svg" version="1.1">
  		<defs>
    		<style type="text/css"><![CDATA[
      			rect.myclass {
        		fill: red;
        		stroke: black;
        		stroke-width: 2
      				}
    			]]>
			</style>
  		</defs>
  		<rect class="myclass" x="200" y="100" width="600" height="300"/>
	</svg>						
							

Style attribute

	<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
		<circle cx="5" cy="5" r="3" style="stroke: #000000 fill: #ff0000;" />
	</svg>