Adding SVG to a webpage
This topic introduces common ways to render SVG in your webpage and assumes that you have basic HTML and JavaScript knowledge.
- Introduction
- Ways to Render SVG
- Inline HTML5
- Inline XHTML
- Stand-Alone SVG
- Embedded
- Plug-in
- Summary
- Related topics
Introduction
If you are just learning about Scalable Vector Graphics (SVG) and you want to experiment with it, one of your first questions might be how to add SVG to a basic webpage. If you take a look at a relatively basic webpage template, you can get a good idea of how to begin.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>My First SVG Page</title>
</head>
<body>
<p>SVG to be inserted here.</p>
</body>
</html>
There are a number of ways to add SVG to this basic template. The following example shows a straightforward way of doing so.
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> -->
<title> My First SVG Page</title>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width="200px" height="200px">
<rect x="0" y="0" width="100%" height="100%"
fill="none" stroke="black"/>
<circle cx="100" cy="100" r="50"
style="stroke: black; fill: red;"/>
</svg>
</body>
</html>
Tip To improve compatibility across modern browsers, save the previous sample code with an xhtml
file extension. By changing the file extension from html
to xhtml
, you effectively transform the template from an HTML document to an XHTML document. This is why the xml
declaration (first line in the previous example) has been added and the meta
element has been commented out. See the following list for more detailed information about the previous example.
<?xml version="1.0" encoding="utf-8" standalone="no"?>
Thexml
declaration is a browser processing instruction that identifies the document as XML/XHMTL. The required version attribute specifies the version of the XML standard that the XML document conforms to. The optionalencoding
attribute indicates to the browser how to interpret the associated bytes of the document based on a particular character set (the default encoding is UTF-8). The optionalstandalone="no"
attribute indicates that the Document Type Definition (DTD) that is specified in theDOCTYPE
element will be used for more than just validation. Be aware that specifyingstandalone=”no”
is actually not necessary. Thestandalone=”no”
value is assumed when an external markup declaration (DTD in this case) is present.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
TheDOCTYPE
declaration is not technically an HTML element. This declaration is an instruction to the web browser, which describes what version of markup language the page is written in. Be aware that the declaration refers to a DTD that specifies the rules for the markup language, so that browsers can render the content correctly. The DOCTYPE also enables you to use page validators. In this case, the XHTML 1.0 Transitional DTD enables all HTML elements and attributes, including presentational and deprecated elements (for example,<font>
). However, frames are not allowed and the markup must be written as well-formed XML.<html xmlns="http://www.w3.org/1999/xhtml">
Thehtml
element indicates to the browser that this is an HTML document in the general sense, and specifically, an XHTML document as indicated byDOCTYPE
. Thexmlns
attribute specifies the XML namespace for the XHTML document. In general, developers should explicitly include the XHTML xmlns declaration when writing XHTML documents.<head>
Thehead
section of a webpage enables you to define page titles, provide search engine information, set page location, add style sheets, write scripts, and so on. (For example,base
,link
,meta
,script
, andstyle
).<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
Themeta
element provides metadata about the document. Metadata is information about the contents of the document (that is not displayed to the reader). This metadata can be used by the browser or other software such as search engines, document management systems, and so on. In the first template (with nosvg
element), the content attribute specifies that the page should first be served (from web server to client) by using an HTTP header calledContent-Type
that has a value oftext/html; charset=utf-8
before the actual page content is delivered by the server. This process enables the browser to correctly render the incoming page data (text/html) by using the correct character encoding (charset=utf-8). In the second XHTML (SVG) sample, themeta
element is commented out because specifying character encoding using themeta
element is ignored in XML/XHML documents, and must be shifted to thexml
declaration. Developers can switch between using themeta
element for HTML and thexml
declaration for XML/XHTML.<title>
Generally, thetitle
element renders its associated text in the browser’s tab.</head>
The closing element forhead
.<body>
Thebody
element is the container for the content of the XHTML document that is displayed.<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200px" height="200px">
Thesvg
element defines the SVG document fragment. Thexmlns
attribute defines the namespace for the SVG fragment. Theversion
attribute indicates the SVG language version to which this document fragment conforms, and thewidth
andheight
attributes define the size of the SVG viewport (a 200 x 200 pixel square, in this case).<rect x="0" y="0" width="100%" height="100%" fill="none" stroke="black"/>
Relative to the SVG viewport, the SVGrect
element draws a black rectangle starting at the upper-left corner of the viewport, or at point (0, 0), that has a maximum width and height. This positioning outlines the given SVG viewport.<circle cx="100" cy="100" r="50" style="stroke: black; fill: red;"/>
Similarly, the SVGcircle
element draws a red circle that has a black border, whose radius is 50 pixels. The circle is centered in the middle of the 200 x 200 pixel SVG viewport.</svg>
The closing element forsvg
.</body>
The closing element forbody
.</html>
The closing element forhtml
.
Ways to Render SVG
There are other methods you can use to render SVG as well. The following table summarizes these methods.
Method | Recommend file extension | Required browser | Pros and cons |
---|---|---|---|
Inline HTML5 | .html | A browser that natively supports inline SVG in HTML5, such as Windows Internet Explorer 9. | Pro: Can take full advantage of HTML5 constructs. Con: Might need to implement fallback code for browsers that do not support inline SVG in HTML5. |
Inline XHTML | .xhtml | A browser that natively supports SVG, such as Internet Explorer 9. | Pro: Many browsers currently support XHTML-based inline SVG. Con: Cannot take advantage of HTML5 constructs. |
Stand-Alone | .svg | A browser that natively supports SVG, such as Internet Explorer 9. | Pro: Can easily be embedded into existing content by using the Embedded method. Con: Cannot take advantage of all HTML/XHTML constructs. |
Embedded | .xhtml | A browser that natively supports SVG, such as Internet Explorer 9. | Pro: Simple to implement and fallback behavior is relatively easy by using embedding. Con: Might be difficult to script SVG content from embedding page. Additionally, some browsers might not support all forms of embedding such as referencing SVG through animg element or through a CSS background-image style. |
Plug-in | .html | A browser that may or may not natively support SVG. | Pro: Browser does not need to support SVG natively. Uniform SVG behavior across browsers. Con: Plug-ins might cause browser instability, W3C SVG specifications might be out of date, and/or support for the plug-in might be discontinued by the plug-in provider (as is the case for the Adobe SVG Viewer plug-in). |
Note Windows Internet Explorer 8 does not natively support SVG and thus requires a plug-in to render SVG. However, by implementing appropriate fallback code (as mentioned later in this topic), you might not need a SVG plug-in.
Examples of each of the above five methods are described in the following section.
Inline HTML5
The following example shows a basic inline HTML5 SVG template. The code example creates a circle in SVG markup and registers the click event. When the circle is clicked, the circle changes size.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<script>
function doCircle(evt)
{
var theCircle = evt.target;
var radius = theCircle.getAttribute("r");
if (radius == 50)
{
radius = 75;
}
else
{
radius = 50;
}
theCircle.setAttribute("r",radius);
}
</script>
</head>
<body>
<svg width="300px" height="300px">
<text x="25" y="50" font-size="24">SVG Circle Element</text>
<text x="25" y="275">Click the circle to change its size.</text>
<circle cx="125" cy="150" r="50"
fill="pink" stroke="green" stroke-width="5"
onclick="doCircle(evt)" />
</svg>
</body>
</html>
The <!DOCTYPE html>
element indicates to the browser that this is an HTML5 document. The <meta http-equiv="X-UA-Compatible" content="IE=9"/>
element is used to force Windows Internet Explorer into IE9 Standards mode for correct rendering on intranet sites. Be aware that for HTML5, the html
element’s xmlns="http://www.w3.org/1999/xhtml"
attribute is not applicable.
Tip As suggested by the above table, save this sample with a html
file extension.
Note For HTML5, SVG content overflows by default whereas in XHTML it is hidden.
Inline XHTML
Because SVG is XML-based, you can add SVG to an XHTML document by using the correct namespaces, as indicated in the following basic inline XHTML template.
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Manipulating the Radius of an SVG Circle</title>
<script language="javascript" type="text/javascript">
<![CDATA[
var red_circle; // The object representing circle.
var r; // The variable representing circle's radius.
window.onload = function() {
red_circle = document.getElementById('redCircle');
r = red_circle.getAttribute("r");
}
function grow() {
r = 2*r;
red_circle.setAttribute("r",r);
}
function shrink() {
r = r/2;
red_circle.setAttribute("r",r);
}
]]>
</script>
</head>
<body>
<svg width="200px" height="200px" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<circle id="redCircle" cx="100" cy="100" r="50"
style="stroke: black; fill: red;"
onmouseover="grow()" onmouseout="shrink()"/>
<rect x="0" y="0" width="100%" height="100%" style="fill: none; stroke: black;"/>
</svg>
</body>
</html>
This code example creates a 200 × 200 pixel viewport and draws a red, 50px radius circle that has a black border. If you move the mouse pointer over the rendered circle, the circle doubles its radius; if you move the mouse pointer off the rendered circle, the circle's current radius reduces by half. The rectangle element is used to outline the boundaries of the viewport.
Tip As suggested in the previous table, save this example with an xhtml
file extension.
Inline XHTML works well but requires the xhtml
file extension and namespaces. Until the recent advent of HTML5, this was the best option.
Stand-Alone SVG
The original intention of SVG was to provide a vector graphic file format by using the svg
file extension. The following example shows a basic stand-alone SVG template.
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
onclick="doSomething(evt)">
<script language="javascript" type="text/javascript">
<![CDATA[
function doSomething(evt)
{
var myRect = evt.target;
if (myRect.id != "redRect")
{
alert("Please click on the rectangle");
document.location.reload();
}
var myWidth = myRect.getAttribute("width");
if (myWidth == 50)
myRect.setAttribute("width", 100);
else
myRect.setAttribute("width", 50);
}
]]>
</script>
<!-- Outline the SVG viewport. -->
<rect x="0" y="0" width="100%" height="100%"
style="fill: none; stroke: black; stroke-width: 5px;" />
<rect id="redRect" x="100" y="100" width="50" height="50"
fill="red" stroke="blue" />
</svg>
This code example alternately expands and contracts the red rectangle with each interior click. If the click is outside the red rectangle, an alert appears and the page reloads.
As noted previously, the standalone="no"
attribute in the xml element (the first line) of the template indicates that the DTD that is specified in the DOCTYPE
element will be used for more than just validation. You do not need to specify standalone=”no”
because this value is assumed when an external markup declaration (DTD in this case) is present.
Tip As suggested in the previous table, save this sample with an svg
extension.
Embedded
The iframe
, embed
, object
, and img
elements and CSS background-image
style can be used, depending on the browser, to embed SVG into a webpage. Be aware that not all of these embedding methods may be available for a particular browser. The following example shows the basic SVG template, which uses the object
element.
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Embedding SVG</title>
</head>
<body>
<h1>Embedding SVG in an XHTML Document</h1>
<p>Embedding the file <em>standAlone.svg</em> using the <strong>object</strong>
element:</p>
<object data="standAlone.svg" width="302px" height="302px" type="image/svg+xml">
<img src="standAlone.png" alt="PNG image of standAlone.svg" />
</object>
</body>
</html>
Tip As suggested in the previous table, save this sample with an xhtml
file extension. Also be aware that the embedded SVG file, standAlone.svg
in this case, must have a svg
file extension.
Assuming the SVG file is not embedded via the img
element or as a CSS background, the embedded SVG file generally contains whatever programming it had, but embedding does not provide an easy way to have programmable interaction between the embedded SVG document and the embedding HTML document unless the embedded SVG file is from the same domain as the embedding page. This method is generally not recommended for programming SVG in a webpage but it's handy for easy insertion of an SVG file and could be useful, with respect to fallback, for earlier browsers, such as Internet Explorer 8, which does not natively support SVG.
Note Because some browsers might not support all forms of SVG embedding, be sure to test across all targeted browsers.
Plug-in
The following list identifies a few reasons why the plug-in solution is not recommended:
- The primary SVG browser plug-in, Adobe SVG Viewer, is no longer supported by Adobe.
- Most modern browsers natively support SVG.
- Third-party plug-ins might introduce browser instability or may cease being supported by the plug-in provider.
Summary
The following tables summarizes the templates reviewed in this topic.
Note Microsoft Internet Information Services (IIS), in its default configuration, does not serve files that use the .svg
file extension. In order to request .svg
web pages from IIS, you must add a "MIME Typing" mapping for .svg
to image/svg+xml
.
For browsers that support SVG and HTML5 natively, the best option is the Inline HTML5 method.
For browsers that do not fully support HTML5 but support SVG natively, use the Inline XHTML or Stand-Alone method, followed by the Embedded method, as applicable.
For browsers that do not support SVG natively, implementing appropriate fallback measures, such as rendering a static image of the SVG graphic, is suggested.
Use <meta http-equiv="X-UA-Compatible" content="IE=9"/>
to enable SVG for an HTML Application (HTA). For more information, see Introduction to HTML Applications (HTAs).