abcid d
abcid d

Reputation: 2947

:Hover to Show an Image on .SVG

I have a .svg icon and want to show an image when I hover the icon. It works on normal icon (red square), but somehow it doesn't work .svg (black circle)!

Please give a hand. Thanks!

jsfiddle

HTML

<div class="red">
</div>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">
  <defs>
    <style>
      .svg-circle {
        fill-rule: evenodd;
        fill: 'black';
      }
    </style>
    <circle id="myDefsCircle" class="svg-circle" r="20" cx="100" cy="100"/>
  </defs>

   <use x="10" y="0"   xlink:href="#myDefsCircle" class="red"/>
</svg>

CSS

.red:hover {
  fill:red;
  background: url('https://www.iconsdb.com/icons/preview/orange/phone-46-xxl.png') no-repeat;
  width: 250px;
  height: 200px;
  background-position: center;
}

.red {
  border: 1px solid red;
  width: 20px;
  height: 20px;
}

Upvotes: 0

Views: 4107

Answers (1)

enxaneta
enxaneta

Reputation: 33044

This is how you can do it with SVG:

In SVG you can't use background images. You need to draw the image using the <image> tag where instead of the src attribute you have to use the xlink:href attribute. Also you can't change the width and height of svg elements in CSS. If you don't want to use Javascript you can't change them.

This is what I've done: I hard coded the width and height but I've made the element transparent: opacity:0 and on hover I'm changing the opacity to 1. I hope this is what you were asking.

svg{border:1px solid}
.test{opacity:0}
.red:hover ~use{opacity:1}
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">
  <defs>
  <circle cx="20" cy="20" r="20" id="myDefsCircle" />  
    
 <symbol id="symb1" viewBox="0 0 40 40">
 <use xlink:href="#myDefsCircle" fill="red" />
 <!--<image xlink:href="https://www.iconsdb.com/icons/preview/orange/phone-46-xxl.png" width="30" height="30" x="5" y="5" />-->
 
 <!--<image xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/cat.svg#blackcat" width="30" height="30" x="5" y="5" />-->
 
 
  <image xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/apple.png" width="30" height="30" x="5" y="5" />
 </symbol>

 </defs>
  
   
  <use xlink:href="#myDefsCircle" x="180" y="180" class="red"  />
  <use xlink:href="#symb1"  class="test" pointer-events="none" width="200" height="200" x="100" y="100" />
</svg>

Upvotes: 4

Related Questions