Styling SVGs
SVG elements can be styled in three ways: directly using presentation attributes, with the style attribute, or via CSS classes. Understanding the difference will help you write cleaner, more maintainable code.
Method 1: Presentation Attributes
The approach you've been using throughout this tutorial is to add styling directly as XML attributes on individual elements. For example, fill="blue" or stroke-width="3". These are called presentation attributes.
Presentation attributes are quick and self-contained, but can become quite verbose when you have many elements with the same styles.
Method 2: CSS Classes
Because inline SVGs live in the HTML document, their elements are part of the browser's DOM (just like div or p elements). This means you can target them with CSS selectors:
This approach is ideal when you have multiple elements sharing the same styles, since it keeps your SVG markup clean and separates presentation from structure.
Method 3: The style Attribute
You can also apply styles using the style attribute, similar to how you would with HTML elements. This is useful for applying a single style to a single element without defining a CSS class:
While this is a perfectly valid way to style SVGs, it's not recommended for more than a few elements, as it can make your code difficult to read and maintain. It's best to use CSS classes instead.
Key Styling Properties
Here are the most common SVG styling properties. All of these work equally as CSS properties or as presentation attributes:
| Property | Description |
|---|---|
fill |
The color used to paint the interior of a shape. Use none for no fill. |
fill-opacity |
Opacity of the fill only (0–1). |
stroke |
The color used to paint the outline of a shape. |
stroke-width |
The thickness of the outline. |
stroke-dasharray |
Creates a dashed outline (e.g., 10 4 = 10px dash, 4px gap). |
stroke-linecap |
End cap style for open lines: butt, round, or square. |
stroke-linejoin |
Corner style where lines meet: miter, round, or bevel. |
opacity |
Overall transparency of the element (fill and stroke combined). |
Which Method Should You Use?
There's no single right answer, but as a general guide:
- Use presentation attributes for unique, one-off styles on individual elements.
- Use CSS classes for shared styles, or any time you want to animate or change styles dynamically with JavaScript.
- CSS will always override presentation attributes if both are present, so they work well together.