72

I try to make an HTML that references to an SVG file, that SVG file is interactive (CSS hover):

  1. If I use <img src="algerie.svg"> I loose the interactivity.

SVG displayed as image embedded in an HTML page

  1. If I open this image in a new tab using dev tool, it becomes interactive.

SVG opened in the browser, showing interactive highlights

  1. If I use:

    <svg viewBox="0 0 512 512">
      <use xlink:href="algerie.svg"></use>
    </svg>
    

Then nothing is shown, and worse, Chrome or Firefox do not detect the file in the network dev tool.

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Abdelouahab
  • 7,331
  • 11
  • 52
  • 82
  • 1
    Does this answer your question? [Do I use , , or for SVG files?](https://stackoverflow.com/questions/4476526/do-i-use-img-object-or-embed-for-svg-files) – BuZZ-dEE Mar 23 '20 at 22:11

1 Answers1

112

You should embed the image by using <object> tag:

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

Refer to this question for the details: Do I use <img>, <object>, or <embed> for SVG files?

Community
  • 1
  • 1
NikitaBaksalyar
  • 2,414
  • 1
  • 24
  • 27
  • 5
    no need to `type="image/svg+xml"`, and it's better to used with `width` and `height` attributes! – Yas Oct 08 '17 at 08:56
  • 11
    Say the SVG has a `` or `` or `` etc. elements. Is it possible to set the `fill` or `stroke` properties for these elements via the `` method? – Hemant Kumar Sep 12 '18 at 07:58
  • 2
    @HemantArora Yes,you can! You can select the element to change its attribute like the normal html element. Besides, you can also bind a class to the element which you want to change. You can check this article for more details [https://benfrain.com/selecting-svg-inside-tags-with-javascript/](https://benfrain.com/selecting-svg-inside-tags-with-javascript/) – UtillYou Dec 10 '18 at 01:46
  • 34
    You actually cannot manipulate any SVG elements when loaded in an OBJECT tag using CSS, because object loads the SVG in it's own document, so CSS has no reach to it. You can however manipulate them using JS, which isn't a very clean solution, plus you have to do other things like wait for the image to load and then manipulate it using JS. Not an good solution in my opinion. – beliha Sep 16 '19 at 12:11