SVG - Accessing individual nodes on xlink:href external source

572 views Asked by At

I was looking at Chris Coier's SVG tricks on CSS-tricks.com and also recently saw him at a conference where he talked about the powers of SVGs and how you can keep all assets in one external svg file.

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

  <symbol id="beaker" viewBox="214.7 0 182.6 792">
    <!-- <path>s and whatever other shapes in here -->  
  </symbol>

  <symbol id="shape-icon-2" viewBox="0 26 100 48">
    <!-- <path>s and whatever other shapes in here -->  
  </symbol>

</svg>

Then, you could just use it like this:

<svg class="icon">
  <use xlink:href="#shape-icon-1" />
</svg>

<svg class="icon">
  <use xlink:href="#shape-icon-2" />
</svg>

Sounds great! BUT, I want to be able to access individual nodes in each symbol and altering them with CSS like I normally would if the SVG was inline in the HTMl.

Take a look at this CodePen: http://codepen.io/chriscoyier/pen/Hwcxp

I thought I could do this, but I can't get it to work:

.icon path{
  fill: green;
}

This does, but this alters the actual source svg

#beaker path {
 fill: green;
}

What I want to do is reuse a graphical element in a grid. And on hover, alter a node in the svg. But only on the node in that particular parent. Not all of them.

1

There are 1 answers

3
Type-Style On

Firefox does some unknown thing where you can style it this way.
edit:

To be more precise:
Firefox seems to turn that symbol kinda into in the DOM. http://codepen.io/Type-Style/pen/EaGbam

.hoverME:hover path, .hoverME:hover circle  {
  fill: red;  
}

This also works with an external file. (Unfortunatly it does not with crossDomain Files)

"But you can insert just the class name of the path. That will work." I mean as long as you stay within the SVG with your selectors it will work.

 circle:hover, path:hover {
  fill: red;  
}