Development Shack Technology Understood

Control SVG Colors using CSS  

Styling an SVG image using CSS can be tricky depending on how you do it.

Take this SVG image:

<svg width="400" height="110">
    <rect width="300" height="100" style="fill: rgb(0,0,255); stroke-width: 3; stroke: rgb(0,0,0)">
</svg>

We can use CSS to style an SVG element:

<svg width="400" height="110">
    <rect width="300" height="100" class="svg-style">
</svg>

<style>
.svg-style {
    fill: red;
    stroke-width: 3;
    stroke: rgb(0, 0, 0);
}
</style>

However, this only works when you inline the SVG image into your HTML

One technique I employed happened to be on a project with angularjs included.

I created a custom attribute to help with this solution:

App.directive('svgSrc', ['$http', function ($http) {
    return {
        'restrict': 'A',
        'scope': {
            src: '@svgSrc'
        },
        'link': function (scope, element, attrs) {

            $http.get(scope.src).then(function (resp) {
                if (resp.status == 200) {
                    element[0].innerHTML = resp.data;
                }
            });

        }
    }
}]);

This will load the SVG image and insert it inline into the DOM.

Here is an example of it's use:

<div class="icon-holder" svg-src="/img/icon.svg"></div>

And an example of your CSS:

.icon-holder .svg-fill {
   fill: white;
}

.icon-holder:hover .svg-fill {
    fill: red;
}

This solution will add a small delay to the loading of every SVG image.

On the other side of the coin, you can change 1 SVG file and every reference to it will be updated.