Home >Web Front-end >CSS Tutorial >Why Doesn\'t :hover Work on SVG Elements, and What\'s the Alternative?

Why Doesn\'t :hover Work on SVG Elements, and What\'s the Alternative?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-29 07:59:11217browse

Why Doesn't :hover Work on SVG  Elements, and What's the Alternative?

SVG USE element and :hover Style – A Browser Support Issue

When attempting to apply :hover style to SVG elements embedded through using , some browsers may encounter limitations.

The Browser Support Limitation

The SVG specification clearly states that CSS2 selectors cannot be applied to the conceptually cloned DOM tree of elements referenced by . This means that :hover cannot be used to target specific elements within the embedded object.

Firefox's Exception

Firefox stands out as an exception, supporting the addressing of "virtual" elements included via wormhole. However, other browsers do not share this capability.

An Alternative Approach Using currentColor

Instead of relying on :hover, a more widely supported approach is to set the referenced element's fill or stroke value to currentColor. By modifying the color property of the element on hover, the referenced element's fill or stroke color changes accordingly.

Here's an example:

<svg version="1.1" width="640" height="480"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">

  <style type="text/css">
    #p0 {fill:currentColor}
    #use1:hover {color:green}
    #use2:hover {color:red}
    #use3:hover {color:blue}
  </style>

  <defs>
    <polygon>

By employing this technique, you can effectively change the fill or stroke color of embedded SVG elements when the element is hovered over, thus mimicking the effect of :hover on these elements.

The above is the detailed content of Why Doesn\'t :hover Work on SVG Elements, and What\'s the Alternative?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn