This post is based on Adding vector graphics to the Web on MDN.
SVG stands for Scalable Vector Graphics, it is an XML-based language for describing vector images, but what is vector images? Let’s compare it with normal images:
There are two types of images popular on the Web, one is the raster image, another is the vector image.
- Raster images are defined using a grid of pixels, popular raster images formats include Bitmap(
.jpg) and GIF(
- Vector images are defined using algorithms, a vector image file contains shape and path definitions that the computer can use to render that image on the screen. It don’t pixellate when zoomed in. The SVG formats allow us to create beautiful vector graphics.
As we talked above, SVG is an XML-based language for describing vector images, just like HTML, but SVG is for marking up graphics, not contents.
You can find many SVG icons on Iconfont, like this heart below:
You can also create simple SVG by handcoding, for example, to create a circle:
<svg viewBox="0 0 100 100" height="200" width="200" xmlns="http://www.w3.org/2000/svg">
The result looks like this:
But if you want to create complex images using SVG, you need some tools like InkScape.
SVG has pros and cons:
- Lighter than raster images most of the time
- Text in vector images remains accessible (which also benefits SEO)
- Easy to get complicated, which leads the growing of file size, and time to be processed in browser
- Sometimes harder to create than raster images
- Not good at complext precision images like photos (use raster images instead)
- Not supported in old browsers (IE8 and below)
There are several different ways to add SVG to HTML pages:
Reference the SVG file in the
src attribute of
altcan be used.
- Can be easily turned into a hyperlink be wrapping an
- The SVG file can be cached by the browser
- CSS can only be used through the inline style in the SVG file.
- CSS pseudoclasses are not available (like
For old browsers that don’t support SVG, you could reference a PNG or JPG using
src and use
srcset (which is supported only in newer browsers) to reference SVG:
If you use SVG as CSS background image, do the following to support old browsers:
You can also copy and paste
<svg> code snippet directly inside your HTML page, the SVG displayed above in the post is using this method, you can inspect them to see what is going on.
- Putting an SVG element inline saves an HTTP request, and therefore it can reduce a bit of loading time.
- Can be easily turned into a hyperlink by wrapping an
- If you are using the same SVG in many places, use multiple same
<svg>s is not a good idea.
<svg>s increases the size of your HTML.
- Not cacheable since it’s not image assets.
- If you have to support obsolescent browsers, you can use the
<foreignObject>element inside the
<svg>, but browsers that support SVG still download all fallback images which cost unnecessary bandwidth.