SVG for Developers: Why You Should Be Using Them If You’re Not Already

#
svg advantages post header img

👋 Hi there. We haven’t met before.

I’ve been working as the team’s first product designer for a few weeks now and thought that now that my hazing has been completed, I’m ready to write for the blog. Or maybe this is part of it? (Kidding, of course.)

I’ve been working behind the scenes on our existing products, giving some TLC to some and improving the user experience of others. I can’t say much more than that really, but exciting things are coming!

For my first post, I thought I’d shed some light on one of my favorite things to happen to the design and developer community in recent years, the adoption of SVGs.

I’ll be taking a look at what SVGs are and why you should start using them, and how to get started even if you’re not a designer yourself.

What is SVG?

Let’s get technical for a second. SVG stands for “Scalable Vector Graphics” and is an XML based, vector image format.

SVGs are predominantly found on the web, and while they have similar uses to JPEG, PNG and WebP image types, their DNA is extremely different.

So why are they different?

Well, traditional image types like JPEG, PNG and GIF are bitmap-based, meaning they consist of a set amount of pixels. Typically, this means that as soon as you start to increase or decrease an image of this type, you are presented with jagged lines, blurry artifacts and a pixelated mess.

We also have the more recent image type of WebP, developed by Google which aims to replace the JPEG, PNG and GIF file formats altogether as a singular more flexible solution. I feel as if discussing WebP and its uses too much would make this article more confusing than helpful as it’s a different subject altogether which I’d be happy to address in another article.

In short, the WebP image type was created to produce much smaller file sizes as well as remove the need to use different image types on the web. It is currently unsupported by Safari and is yet to gain significant traction on the web.

You can find out more about WebP via the Google Developers site

Right, back on track…

So how are SVGs different to bitmap-based images? They are vector-based meaning that they are not resolution dependent. Rather than consisting of pixels, SVGs consists of shapes. This means that they can scale indefinitely without a reduction of quality. Magical.

Okay, so enough about what they are. Why should we use them?

The Awesomeness of SVGs

Pixel-Perfect Scaling!

I touched on this already, but we should quickly reflect on perhaps the biggest benefit to using an SVG over a PNG or JPEG image.

An SVG will scale indefinitely and will remain super sharp at any resolution.

pixel perfect scaling

Smaller File Sizes

This is another big plus. Due to the nature of vector graphics, the data that determines the file size are the layers, effects, masks, colors, and gradients used.

In comparison, bitmap-based images record each and every pixel in the image as well as the number of colors used. Admittedly, it’s a little more complicated than that, but the thing to take away from this is that for the most part, a bitmap-based image will be more expensive than an SVG counterpart.

On top of this, you can make your SVG files even smaller by compressing them with gzip. This means that fewer bytes need to be sent from the server or CDN if gzip compression is enabled.

svg filesize

You Can Stylize an SVG Using CSS

That’s right. And this means that you don’t need to know your way around any design software to make a small edit like a color change. In fact, if you’ve done any sort of front-end development you’ll have no problem adding a gradient to a shape or increasing the thickness of a stroke.

stylize svgs using css

SEO Friendly

As I mentioned at the start of this post, SVGs are XML-based meaning that you can add keywords descriptions and links making the content more recognizable for search engines.

With bitmap-based images, you only have the “title” and “alt” attributes at your disposal for SEO.

SVGs Can Be Embedded Into HTML

Unlike other image types that have to be downloaded from the server as an external resource, SVGs can be embedded into the HTML code. So why is this helpful?

It means you can edit the styling of that SVG using CSS. Also, if you are caching your HTML pages then this means the embedded SVGs will automatically be cached too.

SVGs Are Futureproof

I think this is something that is greatly overlooked. I remember a time before SVG when pixel density was a hot topic in the design community as new cell phones and tablets came on the scene with beautifully rich displays.

This all was great. But it meant that most of the JPEG or PNG images used on websites were not of a high enough resolution anymore and they looked like garbage on handheld devices.

The solution? Create another instance of the image at double the resolution and label it “@2x”. Now the image looked lovely and crisp on the latest iPhone.

If you were sensible, you also detected the user’s resolution in advance and only served the “@2x” image if it was needed as doing so was more expensive in terms of file size.

I’m digressing, but newer screens with higher pixel densities were creating additional headaches for both designers and developers. The very nature of an SVG means that this should no longer be a problem as high-end devices reach resolutions of 6K and beyond.

They Can Be Animated

This is where SVGs really excel. The freedom of being able to edit SVGs using code means you have the ability to animate them. These animations can be as simple or as complicated as you like.

I had a quick browse on Codepen and found this excellent beehive animation by Joy Garcia, all created using SVG.

See the Pen
Beehive SVG Animation
by Joy Garcia (@joygarcia4)
on CodePen.

The best part? The file-size is a minuscule 12 Kilobytes!

Are There Any Disadvantages?

Nothing is perfect. And there are a couple of instances where you would want to potentially opt for bitmap images over SVGs.

Complex Imagery

If you’re dealing with photographs, then you should almost always opt for a bitmap-based image. There are not many instances where you would have an SVG photograph anyway so it’s unlikely you’d ever have to make this decision.

Likewise, there are some instances where a complicated SVG has so many shapes, colors, gradients and masks that it actually starts to outweigh a JPEG or PNG equivalent in filesize. I haven’t encountered this too often, but it is possible.

If you need to use a bitmap image, remember to use PNG if your image has transparency, JPEG if it does not. JPEG images do not support transparency so are better suited to photographs. Alternatively, as we discussed briefly at the beginning of this article, you can simplify the above by using WebP for all bitmap-based images.

Optimization

This relies on some TLC when creating SVGs in a design program such as Adobe Illustrator. Empty group folders and unused layers can add unnecessary junk to the overall file size. On top of that, older SVGs generally have a lot of garbage in the markup and are much more expensive than they need to be. I run all my SVGs through a minifier when I export during the design process to avoid such complications.

There are loads of optimization tools out there including a Node.js tool for optimizing SVG files.

SVGs can massively outweigh the same image as a PNG, if it has not been created or optimized in the correct fashion. But usually, the file size will be smaller. Just don’t be put off if you encounter an individual SVG to be twice the file size of a PNG equivalent.

Browser Support

This is not so much of a problem like it used to be. But, if for some reason you need to support super outdated browsers like Internet Explorer 8, then you may run into some compatibility issues with SVGs.

That being said, you can still go ahead and use SVGs and simply implement JPEG or PNG fallbacks as a failsafe.

SVG Icons Are Your Friend

Icons are where all of the advantages of SVGs really become apparent. No longer do you need multiple icons in different colors and sizes which simplifies the design and development process. To articulate this further, I wanted to revisit what life used to be like before SVGs came along…

A Trip Down Memory Lane

Before SVGs where a thing, icons were honestly a bit of a pain for both designers and developers. More often than not, a product would feature 20+ icons and each icon would require an active state (usually the primary color), an inactive/disabled state and sometimes additional states too (such as a hover state).

As we have discussed already, bitmap images are not editable using CSS so each icon state would require its own file.

I also mentioned that when higher pixel density screens became a thing, we also had to create a “@2x” and “@3x” version of our image assets for higher resolution displays.

I had no intention of doing anything practical with this information, but while writing this section I decided to test how much file size I could save using an icon set of SVGs over bitmap versions.

I have a “favorite” icon from the Material Design that I want in 3 different colors. These are an active state, an inactive state and a disabled state.

svg vs png test exercise

Using the active state of our icon, we can also produce the other 2 icon states by tweaking the CSS styling. So we only need one SVG file to produce all 3 icons!

To create bitmap versions of these icons, we will need a separate file for each icon state.

On top of this, to make the bitmap versions look sharp on all types of devices, we will need to create a set of these icons at double and triple the dimensions of the baseline resolution (“@2x” and “@3x” respectively).

That leaves us with 9 PNG icons to manage as opposed to the 1 SVG file we can use to achieve the same results.

The SVG amounts to a single kilobyte whereas all of the PNG icons add up to 29KB.

Sure, 29KB doesn’t sound like a lot, but here we are talking about a single icon. If we had 30 icons to use, the difference in file size becomes more of an issue…

SVG: 1KB * 30 = 30KB.

PNG: 29KB * 30 = 870KB.

That’s a 2900% increase over the single SVG. Of course, these are averages, but it’s a pretty huge jump in size nonetheless.

svg vs png test result

Hopefully, by now you can now see how much simpler SVGs are to use and manage, particularly with icon sets.

From experience, you can generally expect at least a 50% reduction in overall file-size when opting for SVG icons instead of PNG. Particularly if you are optimizing your SVGs and you want your icons to render perfectly on any type of resolution or display.

SVG Sprites

We use a whole bunch of SVGs on both deliciousbrains.com and spinupwp.com, and we’ve been using a neat SVG workflow to create a sprite from a folder of SVG files, which can be loaded only once on a page load, instead of an HTTP request for each SVG file. We use this Gulp task as part of our asset build task to take all the SVGs in a folder, remove them of unnecessary cruft, and formulate one big SVG in a PHP file, with each individual SVG as a <symbol>:

gulp.task( 'svg', function() {
    return gulp.src( 'assets/svg/*.svg' )
        .pipe( svgmin( {
            plugins: [
                { removeViewBox: false },
                { removeUselessStrokeAndFill: true },
                { removeEmptyAttrs: false },
                { removeUnknownsAndDefaults: false },
                { cleanupIDs: false },
                { removeUselessStrokeAndFill: true }

        } ) )
    .pipe( rename( { prefix: 'icon-' } ) )
    .pipe( svgstore( { inlineSvg: true } ) )
    .pipe( rename( 'svgs.php' ) )
    .pipe( gulp.dest( 'template-parts' ) );
} );

We then include the svgs.php file that this task outputs at the opening of the <body> tag in our theme:

add_action( 'wp_body_open', function() {
    get_template_part( 'template-parts/svgs' );
});

And hide the massive SVG with CSS, so it’s not displayed until we call it into action:

body > svg {
    display: none;
}

Now to the fun part. For example, we have our logo as an SVG as /assets/svgs/logo.svg which gets added to the sprite as <symbol id="icon-logo">, so to render the logo we can simply add this to our HTML in our theme’s template files:

<svg><use xlink:href="#icon-logo" /></svg>

It’s pretty cool!

Where to Get Free SVG Icons

Here a few different sites that I like to use for SVG icons and icon sets. Some require you to credit the author depending on where you use the icon, so look out for that.

Recap

Hopefully, by this point, I’ve made a pretty good case to why you should be thinking about using SVGs if you’re not already. They’re easier to manage, will make your website load faster and you won’t need to update them every time a new resolution display comes onto the market with a higher PPI (pixels per inch).

On top of this, you can animate and make changes to the styling of your SVGs without needing or knowing how to use a design tool like Photoshop or Sketch.

Got any other cool tips or uses for SVG you would like to share? Have any other design questions you’d like me to write about in a future post? Let us know in the comments section below.

About the Author

Lewis Warren

Lewis is a Product Designer from London that loves coffee and dislikes bitmaps. From websites to mobile games, Lewis has years of agency experience working on all kinds of products.