Home > Web Front-end > CSS Tutorial > Why Don\'t :hover Styles Work on SVG `` Elements, and How Can I Work Around This?

Why Don\'t :hover Styles Work on SVG `` Elements, and How Can I Work Around This?

Susan Sarandon
Release: 2024-11-26 03:30:12
Original
1037 people have browsed it

Why Don't :hover Styles Work on SVG `` Elements, and How Can I Work Around This?

Addressing SVG Elements Embedded with Use and :hover Style

Understanding the Problem

When attempting to apply :hover styles to SVG elements embedded using the tag, one may encounter difficulties. This arises from the fact that elements referenced through are not part of the formal document structure, making it challenging to address them directly with CSS selectors.

Why :hover Styles Don't Work

As per the SVG Use Element Specification, CSS selectors cannot be applied to the conceptual DOM tree where the referenced elements reside. This means that :hover pseudoclasses will not work on these elements, preventing you from applying interactive styles.

The Firefox Exception

While most browsers lack support for addressing "virtual" elements embedded via , Firefox stands as an exception. It allows for the modification of fill or stroke colors by setting their values to 'currentColor' in the referenced element and altering the color property of the element on hover.

An Alternative Approach

An alternative method to achieve hover effects on embedded SVG elements involves the utilization of 'currentColor'. By setting the fill or stroke attribute of the referenced element to 'currentColor' and modifying the color of the element on hover, browsers can update the inherited current color. This technique offers a workaround, even though it does not provide the full range of styling capabilities afforded by :hover pseudoclasses.

Example

Consider the following SVG code:

<svg>
  <style>
    #p0 { fill: currentColor; }
    #use1:hover { color: green; }
    #use2:hover { color: red; }
    #use3:hover { color: blue; }
  </style>

  <defs>
    <polygon>
Copy after login

When you hover over each of the elements, their respective shapes will change color to green, red, or blue based on the color specified in their :hover rules.

The above is the detailed content of Why Don\'t :hover Styles Work on SVG `` Elements, and How Can I Work Around This?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template