Styles in SVG often come very close to CSS syntax – sometimes exactly the same, often just different enough to cause confusion.
It’s important to note that here we are talking about rules for appearance used in the SVG code itself, not rules that may be applied to the SVG after it has been embedded on the web page. However, if you come to SVG from an understanding of CSS it is useful to compare and contrast style properties between the two:
SVG | CSS Equivalent |
---|---|
fill | background-color or color ,(depending on context) |
fill-opacity | background-color or color with rgba/hsla,(depending on context) |
opacity
| |
stroke | border-color
|
stroke-width | border-thickness
|
stroke-opacity | border-color with rgba
|
rx, ry | border-radius |
The following properties remain the same in styles implemented in SVG or CSS, although the syntax is slightly different for transformations and dimensions in SVG:
font-family
,font-size
,font-style
,font-variant
andfont-weight
width
andheight
scale
,rotate
,skew
Most of these properties can be applied as part of an SVG style, and if you come from a CSS background, that’s probably the easiest way to approach the code. I’ve used those that must appear in attribute form in the code sample below:
<svg width="300" height="170" style="float: left">
<rect x="10" y="5" rx="15" width="280" height="160" style="fill: #a73838; fill-opacity: 0.65; stroke: #000; stroke-width: 10; stroke-dasharray: 22, 2, 2; ry: 15;"/>
<text x="130" y="115" fill="yellow" font-size="100" style="font-family: Blue Highway, Arial Black, sans-serif; stroke: black; stroke-width: 2;">SVG</text>
</svg><p>Test paragraph</p>
Produces what you see here:
Gradients are substantially different between CSS and SVG, enough to require their own article.
Note that we don’t have to specify units in SVG, at least in the code I’ve shown here: pixels are always assumed.
You should not come away from this article convinced that styles in SVG are simply “CSS done another way”. SVG provides many controls – as you can see, SVG strokes can include many forms of customized dashes, without any of the complications of CSS3’s border-image
– but this should be enough to get you started in styling your SVG content.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.