24 March, 2015
You know the trade-off. Use the img tag to display an SVG, and you get clean markup — at the cost of styling the SVG using its properties like fill, stroke, SVG filters and more.
Using an SVG via an img tag seems practically useless, if the same SVG file requires to have different properties at different locations on your site. For example, your logo in the header may need to be a dark color, and require to be white against a banner below. In such a case, you would be better off manipulating the properties of the SVG like fill and stroke directly via CSS, for each use case.
Today, while chatting with a client for a single page app that we're launching soon (that deals with real time bids for a service), the client mentioned that it would be nice to have a shadow for an SVG on the marketing website.
I was using the SVG inside an img tag for this section, for reasons that were out of my control, i.e. it was easier for the client to update the CMS being used for the marketing site by swapping out the src attribute on the image tag.
The obvious solution would be to add the drop shadow directly to the SVG element. And then I remembered that CSS filters can be used to style just about any element in the DOM. I added a drop-shadow using CSS filters, and it worked, as expected.
The caveat of course, is browser support. However, things don't look so bad from where I'm looking. All Blink and Webkit based browsers support CSS filters, i.e. Chrome, Safari, Opera. So does Firefox (since early Jan, 2015). IE is incorporating support shortly as well.
Since I'd consider a shadow on an icon as progressive enhancement, I'm fine with adopting this method for the current use case. What one needs to be careful about is the current state of the spec, which is at the stage of Working Draft, so keep an eye out for changes, risks and deprecations.
CSS filters will never replace the depth and breadth of what SVG filters are capable of, especially since you can't manipulate parts of an SVG inside an image tag. But they can come in handy as quick fixes.
Here are a few uses for CSS filters I could think of, when using an SVG inside an image tag:
The above would also work on raster images like PNG files. For example, you can add a drop shadow filter to a PNG image and it will respect the transparency of the image, whereas a CSS box-shadow would apply the shadow to the outer boundary of an image. See here for more.
You can take a look at the CodePen demo below to see some examples of how CSS filters can be used for SVGs:
Image source here