How to Add Scalable Vector Graphics to Your Web Page

Craig Buckler
Craig Buckler
Share

In this tutorial, we discuss ways you can add SVG images to your web page. Unlike bitmap images, SVGs are XML markup which describe shapes, lines, and fills so the document can be used in a variety of ways.

In this series, we’ve discussed what SVGs are, why you should consider them and basic vector drawings.

At some point, you’ll want to embed your finely crafted SVG directly into a web page. There are at least six ways to achieve that goal — but all methods have pros and cons.

1. Inline SVG XML Directly Into Your HTML Page

An SVG image can be added as a code island directly within your HTML page using outer <svg> tags:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Embedded SVG</title>
</head>
<body>

  <h1>Embedded SVG</h1>

  <!-- SVG code -->
  <svg width="300px" height="300px"
    xmlns="https://www.w3.org/2000/svg">
    <text x="10" y="50" font-size="30">My SVG</text>
  </svg>

</body>
</html>

This method works in all modern browsers. The SVG becomes part of the page DOM so it can be manipulated with CSS or JavaScript perhaps to add animation or react to click events. (Note that any JavaScript embedded in the SVG itself will be blocked.)

The main disadvantage is that the SVG must be embedded into every page which requires it, and may need to be repeated for reusable icons. This adds to the page weight and, although the HTML may be cached, the SVG code can’t be (easily) reused elsewhere.

One solution to the repeated image issue is to create a hidden SVG block on each page (with CSS display: none). This can optionally contain multiple images referenced using an id:

<svg xmlns="https://www.w3.org/2000/svg" style="display: none;">
  <defs>
    <symbol id="box" viewBox="0 0 32 32">
      <title>box</title>
      <rect width="32" height="32" fill="#00c" />
    </symbol>
    <symbol id="circle" viewBox="0 0 32 32">
      <title>circle</title>
      <circle cx="16" cy="16" r="16" fill="#c00" />
    </symbol>
  <defs>
</svg>

Individual items can then be used any number of times with an SVG use element:

<svg width="20" height="20">
  <use xlink:href="#box" />
</svg>

<svg width="30" height="30">
  <use xlink:href="#box" />
</svg>

<svg width="40" height="40">
  <use xlink:href="#circle" />
</svg>

The original image can still be styled using CSS, although it’s not possible to apply additional styles to the <use> itself.

2. Use an <img> Tag

SVGs can be added to your web page like any other image:

<img src="image.svg" alt="my image" />

The usual width, height, alt and other <img> attributes can be added should you require them.

The browser treats the SVG like any other image. For security reasons, any scripts, external stylesheets, links, and other SVG interactivity will be disabled.

A target anchor can be used if multiple images are defined within a single SVG — such as myimage.svg#circle — but this won’t work in older browsers.

3. Apply a CSS Background Image

SVGs can be used as a CSS background for any element:

#myelement {
  background-image: url('./image.svg');
}

Inline data URIs with UTF8 encoding may also be practical for smaller, regularly used SVGs which are unlikely to change often (and invalidate the whole stylesheet):

.myelement {
  background: url('data:image/svg+xml;utf8,<svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 300 300"><circle cx="150" cy="150" r="100" stroke-width="5" stroke="#f00" fill="#ff0" /></svg>');
}

Like <img> tags, scripts, links, and other types of interactivity are disabled when you use this method.

4. Load in an <iframe>

Browsers can render an SVG document on its own, so you can load an image within an iframe:

<iframe src="./image.svg">
  Your browser does not support iframes.
</iframe>

This may be a practical if you have a portable SVG with its own scripts and styles that you need to isolate from the main page. However, manipulating an SVG image from your main page’s JavaScript will become more difficult, especially if it’s hosted on another domain.

5. Use an <object> Tag

The HTML <object> tag can be used to add an SVG to your page:

<object type="image/svg+xml" data="./image.svg">
  <img src="./fallback-bitmap.png" />
</object>

Fallback text or images can be used within the <object> block in a similar way to iframes.

Styles and scripts within the SVG will run. It’s not possible to style the SVG using CSS in the HTML page, but scripts can manipulate individual elements:

// get first <object>
const objTag = document.querySelector('object');

// wait for SVG to load
objTag.addEventListener('load', () => {

  // reference to SVG document
  const svg = objTag.getSVGDocument();

  // make changes
  Array.from(svg.getElementsByTagName('path'))
    .forEach(p => p.setAttribute('fill', '#00f'))

});

<object> was the most-used option around a decade ago, because it was the only reliable way to use an SVG in old releases of IE.

6. Use an <embed> Tag

I’m including <embed> for completeness but please don’t use it! It’s similar to <object> in that it embeds external content into the page, but was designed to communicate with an external application such as a browser plugin.

<embed type="image/svg+xml" src="./image.svg">
  not supported
</embed>

Since the demise of Flash and Silverlight, modern browsers have deprecated and removed support for browser plugins. Never rely on <embed>.

Which SVG Technique Should You Use?

If you’re using an SVG as an image and don’t need to change the styling or add scripting, an <img> tag or a CSS background is possibly the best option. The file can be cached in the browser and reused on other pages with no further download.

Where you require interactivity, the most popular option is to inline the SVG directly into the HTML. Styles and scripts can manipulate the DOM, links can be added to any shape, and sophisticated SVG filters can be applied to other page elements.

The <object> tag has fallen from favor. However, it remains a viable technique if you want to keep SVGs separate and cacheable, but they require a little JavaScript manipulation.

Iframes may be suitable for some projects, but never use <embed> unless you have the displeasure of coding for an ancient browser.

Frequently Asked Questions (FAQs) about Adding SVG to a Web Page

What are the benefits of using SVG over other image formats on my web page?

SVG, or Scalable Vector Graphics, offer several advantages over traditional image formats like JPEG, PNG, or GIF. Firstly, SVGs are resolution-independent, meaning they maintain their quality regardless of the size or resolution of the screen they’re displayed on. This makes them ideal for responsive web design. Secondly, SVGs are typically smaller in file size, which can help improve your website’s load time. Lastly, SVGs can be manipulated with CSS and JavaScript, allowing for interactive and dynamic graphics.

How can I embed an SVG directly into my HTML?

Embedding an SVG directly into your HTML is quite straightforward. You simply need to include the SVG code within your HTML document. Here’s an example:

<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
In this example, a circle is drawn using SVG. The width and height attributes define the viewbox of the SVG. The cx, cy, and r attributes define the x-coordinate, y-coordinate, and radius of the circle respectively.

Can I use CSS to style SVGs?

Yes, you can use CSS to style SVGs. This is one of the major advantages of using SVGs. You can control the fill color, stroke color, stroke width, and more using CSS. Here’s an example:

svg {
fill: red;
stroke: black;
stroke-width: 2px;
}
In this example, the SVG will be filled with red, have a black stroke, and the stroke width will be 2 pixels.

How can I make my SVGs responsive?

To make your SVGs responsive, you can use the viewBox attribute. The viewBox attribute allows you to specify the aspect ratio and coordinate system of the SVG. By using this attribute, the SVG will scale to fit the width and height of its container while maintaining its aspect ratio. Here’s an example:

<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
In this example, the SVG will scale to fit its container while maintaining its aspect ratio.

Can I animate SVGs?

Yes, you can animate SVGs using CSS animations or JavaScript. This allows you to create interactive and dynamic graphics. Here’s an example using CSS animations:

@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}

svg {
animation: spin 2s linear infinite;
}
In this example, the SVG will continuously spin in a circle.

How can I use SVGs as background images in CSS?

You can use SVGs as background images in CSS by using the url() function. Here’s an example:

body {
background-image: url('image.svg');
}
In this example, the SVG will be used as the background image for the body element.

Can I use SVGs in HTML img tags?

Yes, you can use SVGs in HTML img tags. This is done in the same way as other image formats. Here’s an example:

<img src="image.svg" alt="Description of image">
In this example, the SVG is used as the source for the img tag.

Are there any accessibility considerations when using SVGs?

Yes, there are several accessibility considerations when using SVGs. Firstly, you should always include an alt attribute when using SVGs in img tags. This provides a text alternative for screen readers. Secondly, you can use the title and desc elements within the SVG to provide a title and description for the graphic. Here’s an example:

<svg>
<title>Circle</title>
<desc>A green circle on a yellow background</desc>
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
In this example, the SVG has a title of “Circle” and a description of “A green circle on a yellow background”.

Can I use SVGs in all modern browsers?

Yes, SVGs are supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. However, it’s always a good idea to test your SVGs in multiple browsers to ensure they display correctly.

Can I use SVGs in responsive web design?

Yes, SVGs are ideal for responsive web design. Because they are resolution-independent, they maintain their quality regardless of the size or resolution of the screen they’re displayed on. By using the viewBox attribute, you can ensure your SVGs scale to fit their container while maintaining their aspect ratio.