This is a self Q&A of a handy piece of code I came up with.
Currently, there isn't an easy way to embed an SVG image and then have access to the SVG elements via CSS. There are various methods of using JS SVG frameworks, but they are overly complicated if all you are doing is making a simple icon with a rollover state.
So here is what I came up with, which I think is by far the easiest way to use SVG files on a website. It takes its concept from the early text-to-image replacement methods, but as far as I am aware has never been done for SVGs.
This is the question:
Here's a version for
knockout.js
based on the accepted answer:Important: It does actually require jQuery too for the replacing, but I thought it may be useful to some.
Then just apply
data-bind="svgConvert: true"
to your img tag.This solution completely replaces the
img
tag with a SVG and any additional bindings would not be respected.I realize you're wanting to accomplish this with CSS, but just a reminder in case it's a small, simple image - you can always pop it open in Notepad++ and change the path/whateverelement's fill:
It could save a ton of ugly script. Sorry if it's off-base, but sometimes the simple solutions can be overlooked.
...even swapping multiple svg images might be smaller in size than some of the code snippets for this question.
If we have a greater number of such svg images we can also take the help of font-files.
Sites like https://glyphter.com/ can get us a font file from our svgs.
E.g.
Alternatively you could use CSS
mask
, granted browser support isn't good but you could use a fallbackYou can use data-image for that. using data-image(data-URI) you can access SVG like inline.
Here is rollover effect using pure CSS and SVG.
I know it messy but you can do this way.
You can convert your svg to data url here
If you can include files (PHP include or include via your CMS of choice) in your page, you can add the SVG code and include it into your page. This works the same as pasting the SVG source into the page, but makes the page markup cleaner.
The benefit is that you can target parts of your SVG via CSS for hover -- no javascript required.
http://codepen.io/chriscoyier/pen/evcBu
You just have to use a CSS rule like this:
Note that the
!important
bit is necessary to override the fill color.