HTML - How to render SVG in HTML
Table of Contents
About
How to render svg markup in a HTML page.
You can render SVG markup via:
- embed,
- iframe,
- img,
- CSS background-image
- and svg inclusion.
HTML elements
Svg
A SVG element represents the root of a Scalable Vector Graphics (SVG) fragment.
A svg tag supports the HTML - Sizing (Width and Height attribute)|html width and height attribute]]. This attribute may be overwritten with CSS width and height property
Example:
- The Css
svg {
width: 200px;
height:100px
}
- The HTML
<svg width="50" height="50" viewBox="0 0 150 150" preserveAspectRatio="none">
<circle cx="60" cy="60" r="50" fill="#D5D8CB" stroke="#ECDCC6" stroke-width="5"/>
</svg>
- Output:
In a svg tag, Javascript is executed. You can disallow this execution via:
- a Content Security Policy. Example:
content-security-policy: sandbox; default-src 'none'; script-src 'none'; plugin-types application/pdf; style-src 'unsafe-inline'; media-src 'self'; object-src 'self';
- or by using the image element
Img
SVGs can be included the same way as any bitmap image in a img tag. In a img tag, Javascript is not executed.
<img src="/_media/logo.svg" alt="An example icon" style="width:48px;height:48px" />
Object
Embedded in a document with object
This is not possible to style it from the parent document. Therefore the color should be set up in the SVG
Example:
<object type="image/svg+xml" data="/_media/logo.svg" width="48px"></object>
Library
See software