Abdelouahab
Abdelouahab

Reputation: 7539

How to use external SVG in HTML?

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.

Upvotes: 76

Views: 116505

Answers (2)

Facundo Colombier
Facundo Colombier

Reputation: 3640

The SVG comes as XML so to keep interactivity you can embed the whole content, i.e. using js or just pasting the xml code into your file.

React.js example:

export const MySVGIcon = (props) => <svg {...props}>
...
</svg

and use it like:

<MySVGIcon />

this way you can keep having control over each element in the DOM: events, styles, etc.

Upvotes: 0

NikitaBaksalyar
NikitaBaksalyar

Reputation: 2514

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?

Upvotes: 118

Related Questions