Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1032114 of Adding vector graphics to the Web

  • Revision slug: Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web
  • Revision title: Adding vector graphics to the Web
  • Revision id: 1032114
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

Vector graphics are the ultimate responsive images — they have small file sizes and are highly scalable. In this article we'll show you how to include one in your webpage.

Prerequisites: You should know the basics of HTML and how to insert an image into your document.
Objective: Learn how to embed an SVG (vector) image into a webpage.

What are vector graphics?

On the web, you'll work with two types of image — raster images, and vector images:

  • Raster images are defined using a grid of pixels — a raster image file contains information showing exactly where each pixel is to be placed, and exactly what color it should be. Popular web raster formats include Bitmap (.bmp), PNG (.png), JPEG (.jpg), and GIF (.gif.)
  • Vector images are defined using algorithms — a vector image file contains shape and path definitions that the computer can use to work out what the image should look like when rendered on the screen. The {{glossary("SVG")}} format allows us to create powerful vector graphics for use on the Web.

To give you an idea of the difference between the two, let's look at an example. You can find this example live on our Github repo as vector-versus-raster.html — it shows two seemingly identical images side by side, of a red star witha  black drop shadow. The difference is that the left one is a PNG, and the right one is an SVG image.

Two star images, one raster and one vector. At their default size they look identical

The difference becomes apparent when you zoom in the page — the PNG image becomes pixellated as you zoom in because it contains information on where each pixel should be (and what color) — when it is zoomed, each pixel is simply increased in size to fill multiple pixels on screen, so the image starts to look blocky. The vector image however continues to look nice and crisp, because no matter what size it is, the algorithms are used to work out the shapes in the image, with the values simply being scaled as it gets bigger.

Two star images zoomed in. The raster one on the left starts to look pixellated, whereas the vector one still looks crisp.

Moreover, vector image files are much lighter than their raster equivalents, because they only need to hold a handful of algorithms, rather than information on every pixel in the image individually.

What is SVG?

SVG is an {{glossary("XML")}}-based language for describing vector images. It's basically markup, like HTML, except that you've got many different elements for defining the shapes you want to appear in your image, and the effects you want to apply to those shapes. SVG is for marking up graphics, not content. At the simplest end of the spectrum, you've got elements for creating simple shapes, like {{svgelement("circle")}} and {{svgelement("rect")}}. More advanced SVG features include {{svgelement("feColorMatrix")}} (transform colors using a transformation matrix,) {{svgelement("animate")}} (animate parts of your vector graphic,) and {{svgelement("mask")}} (apply a mask over the top of your image.)

As a simple example, the following code creates a circle and a rectangle:

<svg version="1.1"
     baseProfile="full"
     width="300" height="200"
     xmlns="https://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="black" />
  <circle cx="150" cy="100" r="90" fill="blue" />
</svg>

This creates the following output:

{{ EmbedLiveSample('What_is_SVG', 300, 200) }}

You can handcode SVG in a text editor, but for a complex image you'll want a proper vector graphics editor like Inkscape. Unfortunately, you can't just take vector photos with your phone, but you can use Inkscape's Trace Bitmap feature. Note that complex SVGs may take significant processing time in the browser.

Text in vector images remains accessible (which also benefits your {{glossary("SEO")}}). SVGs lend themselves well to animation via scripting, because each component of the image is represented in the {{glossary("DOM")}}.

In Inkscape, save your files as Plain SVG to save space. Also, please refer to this article describing how to prepare SVGs for the Web.

The quick way: {{htmlelement("img")}}

Simply reference the SVG in an {{htmlelement("img")}} element as usual. 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 the tutorial about <img>.

<img 
    src="equilateral.svg" 
    alt="triangle with all three sides equal"
    height="87px"
    width="100px" />

Pros

  • Quick, familiar image syntax with built-in text equivalent.
  • You can make hyperlinks as usual by nesting <img> inside an {{htmlelement("a")}} element.

Cons

  • You cannot manipulate the image with JavaScript.
  • If you want to control the SVG content with CSS, you must include inline CSS styles in your SVG code. (External stylesheets invoked from the SVG file take no effect.)
  • You cannot restyle the image with CSS pseudoclasses (like :focus).
  • To support pre-SVG browsers (IE 8 and below, Android 2.3 and below), furnish a PNG or JPG in your src attribute and use {{htmlattrxref("srcset", "img")}} (which only recent browsers recognize):
    <img src="equilateral.png" alt="triangle with equal sides" srcset="equilateral.svg">
  • You're also welcome to use SVGs as CSS background images, as shown below. This way is largely subject to the same JavaScript/CSS limitations as the <img> method.
    background: url("fallback.png");
    background-image: url(image.svg);
    background-size: contain;
  • If your SVGs aren't showing up, it's often because your server isn't set up properly. If that's the problem, this article will point you in the right direction.

How to include SVG code inline

Just open up the SVG file in a text editor, copy the entire thing, and paste it into your document. Make sure your code snippet begins and ends with the <svg> tags. Here's a very simple example of what you might paste into your document:

<svg width="300" height="200">
    <rect width="100%" height="100%" fill="green" />
</svg>

Your <svg> tag doesn't need version, baseProfile, or xmlns attributes. You should make sure you clear out Inkscape namespace declarations, because HTML only tolerates XHTML, XLink, MathML, and SVG namespaces. If you want to optimize more thoroughly, try the SVG Optimiser or Scour.

Pros

  • Inlining saves an HTTP request, and therefore can reduce your loading time.
  • You can assign classes and ids to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any SVG presentation attribute as a CSS property.
  • Inlining is the only approach that lets you use CSS interactions (like :focus) and CSS animations on your SVG image (even in your regular stylesheet). However, SMIL animations work with all the methods described in this article.
  • You can make SVGs into a hyperlink with this method.

Cons

  • This method is only suitable if you're using the SVG in only one place. Duplication makes for resource-intensive maintenance.
  • Extra SVG code increases the size of your HTML file.
  • The browser cannot cache inline SVG as it would cache regular image assets.
  • You may include fallback in a {{svgelement("foreignObject")}} element, but browsers that support SVG still download any fallback images. You need to weigh whether the extra overhead is really worthwhile, just to support obsolescent browsers.

How to embed an SVG with {{htmlelement("object")}}

The syntax is quite straightforward, and again, there's a nice way to include a fallback:

<object data="parallelogram.svg"
    width="300"
    height="250"
    type="image/svg+xml">
 
<img src="parallelogram.png"
    alt="quadrilateral with two sets of parallel sides" />
 
</object>

Cons

  • Again, even browsers that support SVG still download any fallback images.
  • You cannot make <object> into a hyperlink. The SVG shows up but does not respond to taps (or clicks).
  • You can style SVG elements with CSS, but either
    • the SVG code must include the CSS rules (e.g., in a <style> element), or
    • the SVG file must link to an external stylesheet. To link to a stylesheet, place this code in the SVG file before all tags:
      <?xml-stylesheet type="text/css" href="svg.css" ?>
      (Do not use this code within inline SVG, because it can break your webpage.)

How to embed an SVG with {{htmlelement("iframe")}}

You can open SVG images in your browser just like webpages. So embedding SVGs with <iframe> is just another version of embedding a webpage inside another webpage.

Here's a quick review:

<iframe src="triangle.svg" width="500" height="500" sandbox>
    <img src="triangle.png" alt="Triangle with three unequal sides" />
</iframe>

iframes do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for iframes altogether.

Moreover, unless the SVG and your current webpage have the same {{glossary('origin')}}, you cannot use JavaScript on your main webpage to manipulate the SVG.

Learn more

Revision Source

<div class="summary">
<p>Vector graphics are the ultimate responsive images — they have small file sizes and are highly scalable. In this article we'll show you how to include one in your webpage.</p>
</div>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisites:</th>
   <td>You should know the <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">basics of HTML</a> and how to <a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML">insert an image into your document</a>.</td>
  </tr>
  <tr>
   <th scope="row">Objective:</th>
   <td>Learn how to embed an SVG (vector) image into a webpage.</td>
  </tr>
 </tbody>
</table>

<h2 id="What_are_vector_graphics">What are vector graphics?</h2>

<p>On the web, you'll work with two types of image — raster images, and vector images:</p>

<ul>
 <li>Raster images are defined using a grid of pixels — a raster image file contains information showing exactly where each pixel is to be placed, and exactly what color it should be. Popular web raster formats include Bitmap (<code>.bmp</code>), PNG (<code>.png</code>), JPEG (<code>.jpg</code>), and GIF (<code>.gif</code>.)</li>
 <li>Vector images are defined using algorithms — a vector image file contains shape and path definitions that the computer can use to work out what the image should look like when rendered on the screen. The {{glossary("SVG")}} format allows us to create powerful vector graphics for use on the Web.</li>
</ul>

<p>To give you an idea of the difference between the two, let's look at an example. You can find this example live on our Github repo as <a href="https://mdn.github.io/learning-area/html/multimedia-and-embedding/adding-vector-graphics-to-the-web/vector-versus-raster.html">vector-versus-raster.html</a> — it shows two seemingly identical images side by side, of a red star witha&nbsp; black drop shadow. The difference is that the left one is a PNG, and the right one is an SVG image.</p>

<p><img alt="Two star images, one raster and one vector. At their default size they look identical" src="https://mdn.mozillademos.org/files/12866/raster-vector-default-size.png" style="display:block; height:112px; margin:0px auto; width:223px" /></p>

<p>The difference becomes apparent when you zoom in the page — the PNG image becomes pixellated as you zoom in because it contains information on where each pixel should be (and what color) — when it is zoomed, each pixel is simply increased in size to fill multiple pixels on screen, so the image starts to look blocky. The vector image however continues to look nice and crisp, because no matter what size it is, the algorithms are used to work out the shapes in the image, with the values simply being scaled as it gets bigger.</p>

<p><img alt="Two star images zoomed in. The raster one on the left starts to look pixellated, whereas the vector one still looks crisp." src="https://mdn.mozillademos.org/files/12868/raster-vector-zoomed.png" style="display:block; height:328px; margin:0px auto; width:677px" /></p>

<p>Moreover, vector image files are much lighter than their raster equivalents, because they only need to hold a handful of algorithms, rather than information on every pixel in the image individually.</p>

<h2 id="What_is_SVG">What is SVG?</h2>

<p><a href="https://developer.mozilla.org/en-US/docs/Web/SVG">SVG</a> is an {{glossary("XML")}}-based language for describing vector images. It's basically markup, like HTML, except that you've got many different elements for defining the shapes you want to appear in your image, and the effects you want to apply to those shapes. SVG is for marking up graphics, not content. At the simplest end of the spectrum, you've got elements for creating simple shapes, like {{svgelement("circle")}} and {{svgelement("rect")}}. More advanced SVG features include&nbsp;{{svgelement("feColorMatrix")}} (transform colors using a transformation matrix,) {{svgelement("animate")}} (animate parts of your vector graphic,) and&nbsp;{{svgelement("mask")}} (apply a mask over the top of your image.)</p>

<p>As a simple example, the following code creates a circle and a rectangle:</p>

<pre class="brush: html">
&lt;svg version="1.1"
     baseProfile="full"
     width="300" height="200"
     xmlns="https://www.w3.org/2000/svg"&gt;
  &lt;rect width="100%" height="100%" fill="black" /&gt;
  &lt;circle cx="150" cy="100" r="90" fill="blue" /&gt;
&lt;/svg&gt;</pre>

<p>This creates the following output:</p>

<p>{{ EmbedLiveSample('What_is_SVG', 300, 200) }}</p>

<p>You can handcode SVG in a text editor, but for a complex image you'll want a proper vector graphics editor like <a href="https://inkscape.org/en/">Inkscape.</a> Unfortunately, you can't just take vector photos with your phone, but you can use Inkscape's Trace Bitmap feature. Note that complex SVGs may take significant processing time in the browser.</p>

<p>Text in vector images remains accessible (which also benefits your {{glossary("SEO")}}). SVGs lend themselves well to animation via scripting, because each component of the image is represented in the {{glossary("DOM")}}.</p>

<div class="note">
<p>In Inkscape, save your files as Plain SVG to save space. Also, please refer to this <a href="https://tavmjong.free.fr/INKSCAPE/MANUAL/html/Web-Inkscape.html">article describing how to prepare SVGs for the Web</a>.</p>
</div>

<h2 id="The_quick_way_htmlelement(img)">The quick way: {{htmlelement("img")}}</h2>

<p>Simply reference the SVG in an {{htmlelement("img")}} element as usual. You will need a <code>height</code> or a <code>width</code> attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please <a href="https://developer.mozilla.org/en-US/Learn/HTML/Howto/Add_images_to_a_webpage">read the tutorial about <code>&lt;img&gt;</code></a>.</p>

<pre class="brush: html">
&lt;img 
    src="equilateral.svg" 
    alt="triangle with all three sides equal"
    height="87px"
    width="100px" /&gt;</pre>

<h3 id="Pros">Pros</h3>

<ul>
 <li>Quick, familiar image syntax with built-in text equivalent.</li>
 <li>You can make hyperlinks as usual by nesting <code>&lt;img&gt;</code> inside an {{htmlelement("a")}} element.</li>
</ul>

<h3 id="Cons">Cons</h3>

<ul>
 <li>You cannot manipulate the image with JavaScript.</li>
 <li>If you want to control the SVG content with CSS, you must include inline CSS styles in your SVG code. (External stylesheets invoked from the SVG file take no effect.)</li>
 <li>You cannot restyle the image with CSS pseudoclasses (like <code>:focus</code>).</li>
</ul>

<div class="note">
<ul>
 <li>To support pre-SVG browsers (IE 8 and below, Android 2.3 and below), furnish a PNG or JPG in your <code>src</code> attribute and use {{htmlattrxref("srcset", "img")}} (which only recent browsers recognize):

  <pre class="brush: html">
&lt;img src="equilateral.png" alt="triangle with equal sides" srcset="equilateral.svg"&gt;</pre>
 </li>
 <li>You're also welcome to use SVGs as CSS background images, as shown below. This way is largely subject to the same JavaScript/CSS limitations as the <code>&lt;img&gt;</code> method.
  <pre class="brush: css">
<code>background: url("fallback.png");</code>
background-image<code>: url(image.svg);
background-size: contain;</code></pre>
 </li>
 <li>If your SVGs aren't showing up, it's often because your server isn't set up properly. If that's the problem, this <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Getting_Started#A_Word_on_Webservers">article will point you in the right direction</a>.</li>
</ul>
</div>

<h2 id="How_to_include_SVG_code_inline">How to include SVG code inline</h2>

<p>Just open up the SVG file in a text editor, copy the entire thing, and paste it into your document. Make sure your code snippet begins and ends with the <code><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg">&lt;svg&gt;</a></code> tags. Here's a very simple example of what you might paste into your document:</p>

<pre class="brush: html">
&lt;svg width="300" height="200"&gt;
    &lt;rect width="100%" height="100%" fill="green" /&gt;
&lt;/svg&gt;
</pre>

<p>Your <code>&lt;svg&gt;</code> tag doesn't need&nbsp;<code>version</code>, <code>baseProfile</code>, or <code>xmlns</code> attributes. You should make sure you clear out Inkscape namespace declarations, because HTML only tolerates XHTML, XLink, MathML, and SVG namespaces. If you want to optimize more thoroughly, try the&nbsp;<a href="https://petercollingridge.appspot.com/svg_optimiser">SVG Optimiser</a> or <a href="https://www.codedread.com/scour/">Scour.</a></p>

<h3 id="Pros_2">Pros</h3>

<ul>
 <li>Inlining saves an HTTP request, and therefore can reduce your loading time.</li>
 <li>You can assign <code>class</code>es and <code>id</code>s to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute#Presentation_attributes">SVG presentation attribute </a>as a CSS property.</li>
 <li>Inlining is the only approach that lets you use CSS interactions (like <code>:focus</code>) and CSS animations on your SVG image (even in your regular stylesheet). However, <a href="https://css-tricks.com/guide-svg-animations-smil/">SMIL animations</a> work with all the methods described in this article.</li>
 <li>You can make SVGs into a hyperlink with this method.</li>
</ul>

<h3 id="Cons_2">Cons</h3>

<ul>
 <li>This method is only suitable if you're using the SVG in only one place. Duplication makes for resource-intensive maintenance.</li>
 <li>Extra SVG code increases the size of your HTML file.</li>
 <li>The browser cannot cache inline SVG as it would cache regular image assets.</li>
 <li>You may include fallback in a {{svgelement("foreignObject")}} element, but browsers that support SVG still download any fallback images. You need to weigh whether the extra overhead is really worthwhile, just to support obsolescent browsers.</li>
</ul>

<ul>
</ul>

<h2 id="How_to_embed_an_SVG_with_htmlelement(object)">How to embed an SVG with {{htmlelement("object")}}</h2>

<p>The syntax is quite straightforward, and again, there's a nice way to include a fallback:</p>

<pre class="brush: html">
&lt;object data="parallelogram.svg"
    width="300"
    height="250"
    type="image/svg+xml"&gt;
 
&lt;img src="parallelogram.png"
    alt="quadrilateral with two sets of parallel sides" /&gt;
 
&lt;/object&gt;

</pre>

<h3 id="Cons_3">Cons</h3>

<ul>
 <li>Again, even browsers that support SVG still download any fallback images.</li>
 <li>You cannot make <code>&lt;object&gt;</code> into a hyperlink. The SVG shows up but does not respond to taps (or clicks).</li>
 <li>You can style SVG elements with CSS, but either
  <ul>
   <li>the SVG code must include the CSS rules (e.g., in a <code>&lt;style&gt;</code> element), or</li>
   <li>the SVG file must link to an external stylesheet. To link to a stylesheet, place this code in the SVG file before all tags:
    <pre class="brush: xml">
&lt;?xml-stylesheet type="text/css" href="svg.css" ?&gt;</pre>
    (Do not use this code within inline SVG, because it can break your webpage.)</li>
  </ul>
 </li>
</ul>

<h2 id="How_to_embed_an_SVG_with_htmlelement(iframe)">How to embed an SVG with {{htmlelement("iframe")}}</h2>

<p>You can open SVG images in your browser just like webpages. So embedding SVGs with <code>&lt;iframe&gt;</code> is just another version of <a href="https://developer.mozilla.org/en-US/Learn/HTML/Howto/Embed_a_webpage_within_another_webpage">embedding a webpage inside another webpage.</a></p>

<p>Here's a quick review:</p>

<pre class="brush: html">
&lt;iframe src="triangle.svg" width="500" height="500" sandbox&gt;
    &lt;img src="triangle.png" alt="Triangle with three unequal sides" /&gt;
&lt;/iframe&gt;</pre>

<p><code>iframe</code>s do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for <code>iframe</code>s altogether.</p>

<p>Moreover, unless the SVG and your current webpage have the same {{glossary('origin')}}, you cannot use JavaScript on your main webpage to manipulate the SVG.</p>

<h2 id="Learn_more">Learn more</h2>

<ul>
 <li>{{htmlelement("iframe")}}</li>
 <li>{{htmlelement("object")}}</li>
 <li>{{htmlelement("img")}}</li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Getting_Started">SVG tutorial</a> on MDN</li>
 <li><a href="https://thenewcode.com/744/Making-SVG-Responsive">Quick tips for responsive SVGs</a></li>
 <li><a href="https://tympanus.net/codrops/2014/08/19/making-svgs-responsive-with-css/">Sara Soueidan's tutorial on responsive SVG images</a></li>
 <li><a href="https://www.w3.org/TR/SVG-access/">Accessibility benefits of SVG</a></li>
 <li><a href="https://css-tricks.com/scale-svg/">How to scale SVGs </a>(it's not as simple as raster graphics!)</li>
 <li><a href="https://www.w3.org/TR/SVG/">SVG specification</a></li>
</ul>
Revert to this revision