Marty's Blog

Manipulating SVGs using CSS

March 24, 2019

At the company I currently work for, I’ve been experimenting with using SVGs to show real-time theme updates as a user changes the theme colours in their branding settings. A more traditional approach would require using a set of <div> and <span> elements with border or background color CSS attributes to achieve this. I opted instead to try using SVGs instead, since path and color manipulation seemed to be one of their strong points. Here’s a very basic example SVG:

After inspecting the SVG structure using the browser’s devtools, I can target the <path> element I care about in CSS and modify the fill and stroke attributes like so:

#arbitrary-id-of-path-element {
  fill: hsla(335, 52%, 89%, 1);
  stroke: hsla(335, 52%, 56%, 1);

This gives me an SVG that looks like this:

Pretty simple! It also allows me to export an SVG from a visual design file and manipulate in the browser. Very cool.

Kyle Mathews

Written by Marty Penner who likes race cars, drums, and works in London, Ontario, Canada building useful things. You should follow him on Twitter or something