2

I have a pretty simple little SVG. It shows a small grid of light gray dots, and on mouse hover the dots turn a dark gray, triggered by some CSS embedded in the SVG file:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by IcoMoon.io -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="12" height="32" viewBox="0 0 12 32">
  <defs>
    <style type="text/css">
      #handle path {
        fill: #999;
        stroke-width: 5px;
        stroke: transparent;
      }
      #handle:hover path {
        fill: #333;
      }
    </style>
  </defs>
  <g id="handle">
    <path d="M0,2h4v4h-4v-4z"></path>
    <path d="M0,10h4v4h-4v-4z"></path>
    <path d="M0,18h4v4h-4v-4z"></path>
    <path d="M0,26h4v4h-4v-4z"></path>
    <path d="M8,2h4v4h-4v-4z"></path>
    <path d="M8,10h4v4h-4v-4z"></path>
    <path d="M8,18h4v4h-4v-4z"></path>
    <path d="M8,26h4v4h-4v-4z"></path>
  </g>
</svg>

However, when I embed the SVG in an HTML page via an <img> tag, it will show my SVG with the basic fill: #999 applied, but the :hover styles stop working altogether (demo: https://plnkr.co/edit/yqR5bZEVEt2ZjpKGXeSb).

I get that I can't use CSS in style tags or external stylesheets to style SVG elements included via an <img> tag, but I was hoping that CSS embedded right in the SVG file itself would still work, and it half does. Are browser events not passed properly to SVG files? Is what I'm trying to do just impossible?

Ken Bellows
  • 6,711
  • 13
  • 50
  • 78

1 Answers1

4

The img tag doesn't allow interactive svg's. Try changing the img tag with an object tag. This will make the svg interactive.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

<body>
  <object type="image/svg+xml" data="dots.svg"></object>
</body>

</html>

DEMO: https://plnkr.co/edit/i9VCecx2NxIHMaSr2lmB?p=preview

More information on types of tags to use with SVG in this question.

Community
  • 1
  • 1
Daniel Higueras
  • 2,404
  • 22
  • 34
  • Hello and thanks for the solution. So if we only want to use the svg file twice on the page , what do you suggest to make it more optimal? : 1)Create two separate svg files and customize each one as needed --- or --- 2)Just have one svg file and customize it in two places with your solution – Ali Rezaie Feb 27 '20 at 08:01