Joey Joey - 1 year ago 124
HTML Question

How to style SVG with external CSS?

I have several SVG graphics I'd like to modify the colors of via my external style sheets - not directly within each SVG file. I'm not putting the graphics in-line, but storing them in my images folder and pointing to them.

I have implemented them in this way to allow tooltips to work, and I also wrapped each in an

tag to allow a link.

<a href='' target='_blank'><img class='socIcon' src='images/socYouTube.svg' title='View my videos on YouTube' alt='YouTube' /></a>

And here is the code of the SVG graphic:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="stylesheets/main.css" type="text/css"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "">

<svg version="1.1" id="Layer_1" xmlns="" xmlns:xlink="" viewBox="0 0 56.69 56.69">
<path d="M28.44......./>

I put the following in my external CSS file (main.css):

.socIcon g {fill:red;}

Yet it has no effect on the graphic. I also tried .socIcon g path {} and .socIcon path {}.

Something isn't right, perhaps my implementation doesn't allow external CSS modifications, or I missed a step? I'd really appreciate your help! I just need the ability to modify the colors of the SVG graphic via my external stylesheet, but I cannot lose the tooltip and link ability. (I may be able to live without tooltips though.) Thanks!


Your main.css file would only have an effect on the content of the SVG if the SVG file is included inline in the HTML:

  <svg version="1.1" id="Layer_1" xmlns="" xmlns:xlink="" viewBox="0 0 56.69 56.69">
      <path d="M28.44......./>

If you want to keep your SVG in files, the CSS needs to be defined inside of the SVG file.

You can do it with a style tag:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
<svg xmlns="" version="1.1"
     width="50px" height="50px" viewBox="0 0 50 50">
    <style type="text/css"><![CDATA[
      .socIcon g {
    <path d="M28.44......./>

You could use a tool on the server side to update the style tag depending on the active style. In ruby you could achieve this with Nokogiri. SVG is just XML. So there are probably many XML libraries available that can probably achieve this.

If you're not able to do that, you will have to just have to use them as though they were PNGs; creating a set for each style, and saving their styles inline.