Home > front end >  Selecting a class within a used defs/symbol
Selecting a class within a used defs/symbol

Time:04-03

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  x="10" y="10" width="20" height="10" />
      <rect  x="10" y="20" width="20" height="10" />
    </g>
  </defs>
  <use xlink:href="#house-def" />
  <use xlink:href="#house-def"  transform="translate(30)" />
  
</svg>

Is this even possible?

Thanks for your help.

CodePudding user response:

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  x="10" y="10" width="20" height="10" />
      <rect  x="10" y="20" width="20" height="10" />
    </g>
  </defs>
  <use  xlink:href="#house-def" />
  <use xlink:href="#house-def"  transform="translate(30)" />
  
</svg>

  • Related