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.
Example:
<object type="image/svg+xml" data="/_media/logo.svg" width="48px"></object>
For security reason, the svg is in a top level content, meaning that:
- you can't access the page from svg script
- the style from the parent don't apply to the object
Video
You can embedded an SVG animation is embedded in a video element
Example:
<video src="/_media/logo.svg" type="image/svg+xml"></video>
For security reason, the svg is in a top level content, meaning that:
- you can't access the page from svg script
- the style from the parent don't apply to the object
Security
Note that if an SVG is embedded in a object or video element, the user agent (browser) would not give it access to the DOM of the outer page.
Therefore:
- From the perspective of scripts in the SVG resource, the SVG file would appear to have no parent (ie to be in a lone top-level browsing context)
- This is not possible to style it from the parent document. Therefore the color should be set up in the SVG
Library
See software