I’m working on a site and using some SVG icons in it. I just latched on to the idea of applying css to svg’s, which is good for things like icons, as they can change on hover and suchlike.
At first I was using them just like any other image in an <img> tag. I then read that you must use in-line <svg> tags or <object> to apply css to them.
The only way I can get the css to work is if I paste the svg data into the svg tags on the html page.
Ideally what I want is to still use an external file for the images, but if I try that, the css no longer works on them.
How do you make this work?
This is how I tried adding the file:
I did not mention, which is probably the root of the problem, that when I try to use the external file in <svg><image></svg> tags, I can’t even get it to display the image. Clearly I’m doing it wrong some how. I have also tried putting it in <use> tag, but that didn’t work either.
What is the correct way to add an external svg file and have the global css file affect it?
First things first. I can’t get the image to even display using <svg> tags, so I think I will need to deal with that first, and deal with the css after that.
One method which I did get to work was using php to add the svg:
The effective result is the same as just pasting the svg code in the html doc, but at least the source php file is tidier and the css works on it.
For an example of my intentions, say I want a “click to call” button and I want to have a hover state for it.
I can easily change the background by selecting a:hover but I also want to change the icon’s fill.
In one test, using the full svg code in-line, I got it to change by adding a class to the path element and targeting that .icon:hover but of course it only changes when my mouse is over the actual path, not the whole anchor element or icon background.
Sam, my understanding is that if you have an external SVG image then you do treat it just as you would any other img file. The thing is that as an SVG image is an XML document there are other things you can do to it. This might help.
I did already read that, that’s where I got the idea of using php to insert it. I have yet to try using <object> maybe that will work?
Though I’m thinking the php method may be something I can live with, as it does create in-line svg, but still uses an external file and does not clutter my source code too much.
I think some stuff I read led me to believe you could, but maybe they were linking to the css file in the svg. But I see the logic in how it does not work.
Still does not explain why I can’t even display the image in svg tags, though I probably won’t use that now, since the css will have to go in the svg file, and I refer to keep it in one place, or if I link to the css file in the svg file, will I load the css twice?
Probably go with the php option, it works.