简体   繁体   中英

Inline SVG <use> removes prior :hover fill

I want to change the fill of a SVG on hover on one of the parent element. Initially I copied the full svg inside the element:

<div class="topMenu__item">
    <div class="topMenu__item__icon">
        <svg>
            <g><path d="..." /></g>
        </svg>
    </div>
</div>

And the bellow :hover from css worked perfectly:

.topMenu__item:hover svg path {
    fill:yellow;
}

But for better maintenance I switched to using <use> and defining the svg at the end of the html.

<div class="topMenu__item">
    <div class="topMenu__item__icon">
        <svg>
            <use xlink:href="#home-icon"></use>
        </svg>
   </div>
</div>

The define looks like this:

<svg style:"display: none;">
    <defs><g id="home-icon"><path d="..." /></g></defs>
</svg>

Doing so, :hover does not work anymore. Why is this and how can I correct it?

I believe this is what you are looking for: https://codepen.io/PhilC77/pen/drMgRY

<head>
<style type="text/css">
  .myIcon {
    display: inline-block;
    background-repeat: no-repeat;     
  }

  .testInner {
    fill: green;
  }

  .testInner:hover,
  .getGoogle:hover {
    fill: violet;
  }
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
  <defs>
    <symbol id="myicon-checkmark" viewBox="0 0 32 32">
      <title>checkmark</title>
      <path d="M 16 3 c -7.18 0 -13 5.82 -13 13 s 5.82 13 13 13 s 13 -5.82 13 -13 s -5.82 -13 -13 -13 Z M 23.258 12.307 l -9.486 9.485 c -0.238 0.237 -0.623 0.237 -0.861 0 l -0.191 -0.191 l -0.001 0.001 l -5.219 -5.256 c -0.238 -0.238 -0.238 -0.624 0 -0.862 l 1.294 -1.293 c 0.238 -0.238 0.624 -0.238 0.862 0 l 3.689 3.716 l 7.756 -7.756 c 0.238 -0.238 0.624 -0.238 0.862 0 l 1.294 1.294 c 0.239 0.237 0.239 0.623 0.001 0.862 Z" />
    </symbol>
  </defs>
</svg>

<h4 style="color: blue">Quick explanation of the hover fill concept. Of course you need to format the div ect.</h4>
<h3>Just Icon:</h3>
<div class="testInner">
  <svg class="myicon myicon-checkmark">
    <use xlink:href="#myicon-checkmark"></use>
  </svg>
</div>

<h3>Icon w/Redirect</h3>
  <a href="https://www.google.com/" title="Redirect to Google" target="_blank" class="getGoogle">
    <svg class="myicon myicon-checkmark">
      <use xlink:href="#myicon-checkmark"></use>
    </svg>
  </a>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM