Styling Elements

There are three different ways you can style an SVG element: using individual attributes, using the style attribute and using CSS. My preferred method is to use CSS, which, like CSS for HTML, has the advantage of making it easy to change the styling of multiple elements at once. I will also use individual attributes when it is simpler and if I intend to change the styling with a script. I avoid using the style attribute and can see no reason to use it.

Individual attributes

You can add attributes to elements to control it's style. For example, adding stroke-width="2" to an element will change the width of its stroke to 2 pixels. The most common styling attributes are:

  • fill = "colour" (default = "black")
  • stroke = "colour" (default = "none")
  • stroke-width = "number" (default = "1")
  • opacity = "number" (default = "1")
  • font-family = "font-name(s)" (default = [variable])
  • font-size = "number" (default = "medium")

You can find a complete list of all the styles here.

The style attribute

The style attribute takes all the individual attributes and concatenates them into the value of a single attribute. Different styles are separated by a semi-colon (;) and the key is separated from the value with a colon(:). For example, you could create a blue circle with a thick red border, like this:

<circle cx="40" cy="40" r="10" fill="blue" stroke="red" stroke-width="3"/>

Or like this:

<circle cx="40" cy="40" r="10" style="fill:blue; stroke:red; stroke-width:3;"/>

Although it can be more compact to write a lot of styles this way, it is harder to read and much harder to change with a script.

To be continued...

An example using CSS:

Post new comment

The content of this field is kept private and will not be shown publicly.