About

How to render svg markup in a HTML page.

You can render SVG markup via:

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:

content-security-policy: sandbox; default-src 'none'; script-src 'none'; plugin-types application/pdf; style-src 'unsafe-inline'; media-src 'self'; object-src 'self';

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" />
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='17' viewBox='0 0 17 17'%3E%3Cg%3E%3C/g%3E%3Cpath d='M17 16v1h-17v-1h17zM12 10h2v5h1v-6h-4v6h1v-5zM7 7h2v8h1v-9h-4v9h1v-8zM2 3h2v12h1v-13h-4v13h1v-12z' /%3E%3C/svg%3E" alt="An svg data url scheme example" 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