Skip to main content

Styling SVGs inside Image Tags

You know the trade-off. Use the img tag to display an SVG, and you get clean markup but 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 useless if the same SVG file requires different properties at different locations on your site. For example, the same icon is a different color in the header and footer. In such a case, you're better off manipulating the properties of the SVG like fill and stroke directly via CSS.

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 image 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 January 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:

  • - Inverting a logo color. You could invert a logo's color from black to white, by manipulating the brightness value.
  • - Changing an icon to greyscale or sepia on hover.
  • - Going from a state of unblur to a state of blur on a keyframe animation

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.

Take a look at the CodePen demo below to see examples of how CSS filters can be used for SVGs.

Credits

Related Tags

SVG CSS Filters ALL TAGS