Render SVG on webpage

There are several ways to render an SVG on a webpage:

Inline SVG

Given an SVG of a magenta square:

To inline SVG, all you need to do is to insert it into the HTML:

  <rect width="50" height="50" style="fill: #b0b;" />


If the SVG is a file:

It can be loaded as an image:

<img src="" />

Data URI

Inlining an SVG in the data URI is another way to render it. The advantage is it loads faster (since there’s no request). The disadvantage is it can’t be cached and the size is larger than the original.


To embed an SVG in an image data URI:

  src="data:image/svg+xml,<svg xmlns=''><rect width='50' height='50' /></svg>"

The data URI scheme is as follows:


Note: I left charset blank in my example.

As a result, the following is required for the image to render correctly:

data:image/svg+xml,<svg xmlns=''><!-- content --></svg>

However, there’s a catch.


To embed an SVG in a CSS background-image:

.square {
  background-image: url('data:image/svg+xml,<svg xmlns=""><rect width="50" height="50" /></svg>');

However, there’s a catch.


The one catch with data URI is that certain characters need to be encoded.

For example, the following image will fail to load:

  src="data:image/svg+xml,<svg xmlns=''><rect width='50' height='50' style='fill: #b0b;' /></svg>"

The reason is because of the reserved # character. If # is replaced with %23, the image will render.


Converting the SVG to base64 is one way to go around encoding issues:


Here, we had to specify the base64 charset in the data URI scheme.

The one disadvantage of base64 is that the data becomes more than 2x larger.


Please support this site and join our Discord!