Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG CSS transition not working on `use` element (Chrome)

I'm unable to get a CSS transition to work on a use element inside of an SVG.

It works on the original SVG, but not when I use use. See below.

This appears to be Chrome specific (both examples work in FF).

.stretched-rect {
  width: 50px;
  height: 50px;
}
.stretched-rect svg {
  width: 100%;
  height: 100%;
}

.stretched-rect {
  --fill-color: red;
}
.stretched-rect:hover {
  --fill-color: blue;
}
  Example with original svg (this works):
  <div class="stretched-rect">
    <svg viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" style="fill: var(--fill-color); transition: 1s fill;"/>
    </svg>
  </div>
  
  <br><br>
  <!-- Define SVG, so we can use it with `use` -->
  <svg style="display: none;">
    <symbol id="svg-rect" viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" style="fill: var(--fill-color); transition: 1s fill;"/>
    </symbol>
  </svg>
  
  Example using "use" (this does not work):
  <div class="stretched-rect">
    <svg><use xlink:href="#svg-rect"/></svg>
  </div>
like image 622
JS_Riddler Avatar asked Nov 01 '25 06:11

JS_Riddler


1 Answers

As noted by others, this appears to be a bug in Chrome. See below for workaround.

As I've commented: instead of styling the rect in the symbol you can apply the styles to the use element: Delete the style from the symbol's rect and paste it to the use element:

.stretched-rect {
  width: 50px;
  height: 50px;
}
.stretched-rect svg {
  width: 100%;
  height: 100%;
}

.stretched-rect {
  --fill-color: red;
}
.stretched-rect:hover {
  --fill-color: blue;
}
Example with original svg (this works):
  <div class="stretched-rect">
    <svg viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" style="fill: var(--fill-color); transition: 1s fill;"/>
    </svg>
  </div>
  
  <br><br>
  <!-- Define SVG, so we can use it with `use` -->
  <svg style="display: none;">
    <symbol id="svg-rect" viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" />
    </symbol>
  </svg>
  
  Example using "use" (this is working now):
  <div class="stretched-rect">
    <svg><use xlink:href="#svg-rect" style="fill: var(--fill-color); transition: 1s fill;"/></svg>
  </div>
like image 194
enxaneta Avatar answered Nov 03 '25 22:11

enxaneta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!