Modify SVG with CSS Variables

Well we all know about SVG images , and to render the SVG images we use html <img> tag
<img src=”path/to/myImage.svg” alt=”image”>
So the challenge here is, if you have myImage in blue color and you also want to add the same image but in red color

There are multiple way to achieve this
1. Add two SVG files myImage.svg and myImageinRed.svg .
2. Add external libraries which will convert the images into font-icons (e.g Icomoon , if it is a react project then you can use react-svg) to change the fill, stroke opacity property etc of the image.
The above two mentioned methods will add to the code bundle size.
So is there any way i can still use just one image and alter the properties to make blue image to red or vice versa.
Yes there is a way , We are going to implement the <use> element and css variables in SVG to make it possible .
Let’s deep dive into the code.
Considering the Code directory looks like this:

1. Modifying the SVG/ Referencing css variables in SVG.
Okay so we have our arrow-left.svg image here as :
<svg width="21px" id="arrowLeft" height="15px" viewBox="0 0 21 15" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(-198.000000, -107.000000)" stroke="blue">
<g transform="translate(198.000000, 107.000000)">
<line x1="20.5" y1="7.5" x2="0.5" y2="7.5" id="Path"></line>
<polyline id="Path" stroke-linecap="square" points="7.5 14.5 0.5 7.5 7.5 0.5"></polyline>
</g>
</g>
</g>
</svg>
the stroke color is blue and id is arrowLeft.
Now we will add a variable here so that we can change the stroke color using style
<svg width="21px" id="arrowLeft" height="15px" viewBox="0 0 21 15" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(-198.000000, -107.000000)" style="stroke: var(--color)">
<g transform="translate(198.000000, 107.000000)">
<line x1="20.5" y1="7.5" x2="0.5" y2="7.5" id="Path"></line>
<polyline id="Path" stroke-linecap="square" points="7.5 14.5 0.5 7.5 7.5 0.5"></polyline>
</g>
</g>
</g>
</svg>
2. Integrate the SVG in HTML .
To reference the SVG file in the html we will use <use> element.
<svg class="arrow">
<use xlink:href="images/arrow-left.svg#arrowLeft"></use>
</svg>
<svg class="arrow_in_red">
<use xlink:href="images/arrow-left.svg#arrowLeft"></use>
</svg>
in order to access the content the of svg we will always use the id of <svg> tag .
3. Add CSS
Now we have to add the style.
<style>
svg.arrow {
--color: blue;
}
svg.arrow:hover {
--color: yellow;
}
svg.arrow_in_red {
--color: red;
}
</style>
BOOMM!!! IT IS DONE.
In this article i have just talked about stroke property, but you can manipulate other properties too using css variables. Just follow the same approach.
Okay Bye!!