Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use external SVG in HTML?

Tags:

html

css

svg

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.

like image 439
Abdelouahab Avatar asked Feb 21 '15 23:02

Abdelouahab


People also ask

How do I add external SVG to HTML?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

Can I use SVG in IMG tag?

The quick way: img elementTo embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.

Why is SVG not showing in HTML?

If you are trying to use SVG like <img src="image. svg"> or as a CSS background-image , and the file is linked to correctly and everything seems right, but the browser isn't displaying it, it might be because your server is serving it with an incorrect content-type.

How does SVG work in HTML?

SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element. In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.


1 Answers

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?

like image 81
NikitaBaksalyar Avatar answered Sep 26 '22 04:09

NikitaBaksalyar