why doesn’t hover work with symbols in svg?

This is actually an interesting case, and while Temani Afif gave the right solution, I think it is worth a few more words in a separate answer.

First off, the question is not where the <style> tag sits. It could really be anywhere. The real question is raised by the :hover selector.

<svg style="display: none">
  <symbol id="rectangle">
      <style>
        #myRect {
          fill: blue;
        }
        #myRect:hover {
          fill: red;
        }
      </style>
      <rect id="myRect" width="300" height="100" />
  </symbol>
</svg>

<svg width="400" height="110">
    <use href="#rectangle"></use>
</svg>

The previous SVG 1.1 spec had a short paragraph that said “CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree”, but the SVG 2 spec dropped that sentence.

It now has a lot to say about how style inheritance works for <use> elements. but all of it concerns the question: “If there are style rules for the corresponding element (the <symbol>), how are they applied to the shadow instance (what is inside the <use>)?”

But one question I really could find no answer to is: If a pseudo-class state applies to a shadow host, can the shadow instance elements also have that state? Or, to state it more clearly: If a pointer hovers over a <use> element, does it also hover over the elements inside the shadow tree?

There are no obvious answers in CSS Selectors or CSS Scoping, to name the other two relevant specs. And while Temani Afif alludes to the second one (and what was proposed when ::shadow was removed), this is not the same: nobody tries to select into the shadow tree, it is just that the rule selects a corresponding element.

That is where Firefox answers “yes” and Chrome answers “no”. Which one is the bug? Interestingly, I could not find a bug report in either of the bug trackers.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top