Search code examples
csssvgsymbols

Selecting a class within a used defs/symbol


I'm trying to alter the colours of a multi-element defs, based on the enclosing CSS class. So far I've had zero success. I started out using a symbol, then changed it to a defs with a g in it.

I've put together an example codepen: addressing a class within a defs The square on the right should be green on top and yellow on the bottom.

.rect1 { fill: red; }
.rect2 { fill: yellow; }
.morph .rect1 { fill: green; }

rect { stroke: black; }
svg { background-color: lightblue; }
<svg viewBox="0 0 100 100">
  <defs>
    <g id="house-def">
      <rect class="rect1" x="10" y="10" width="20" height="10" />
      <rect class="rect2" x="10" y="20" width="20" height="10" />
    </g>
  </defs>
  <use xlink:href="#house-def" />
  <use xlink:href="#house-def" class="morph" transform="translate(30)" />
  
</svg>

Is this even possible?

Thanks for your help.


Solution

  • Instead of trying to change the color of the rect1 change the fill of the use elements:

    use{ fill: red; }/*will fill red both use elements*/
    .rect2 { fill: yellow; }/*will fill yellow the .rect2 inside defs*/
    .morph { fill: green; }/*will fill green the second use element overwritting the fill:red from the first roule.*/
    
    rect { stroke: black; }
    svg { background-color: lightblue; }
    <svg viewBox="0 0 100 100">
      <defs>
        <g id="house-def">
          <rect class="rect1" x="10" y="10" width="20" height="10" />
          <rect class="rect2" x="10" y="20" width="20" height="10" />
        </g>
      </defs>
      <use class="a" xlink:href="#house-def" />
      <use xlink:href="#house-def" class="morph" transform="translate(30)" />
      
    </svg>