SVG Overview
what, where, why, how

RESOURCES


SVG EDITORSSVG OverviewMore...

SVG EDIT

Powerful SVG-Editor for your browser

https://deliciousbrains.com/svg-advantages-developers/

What is an SVG File Used For and Why Developers Should be Using Them

The adoption and adaptation of SVGs is without a doubt one of my favorite things to happen to the design and developer community in recent years.

As a designer, they were the aspirin to many a headache that always occurred during the development handover.

Today 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.

And in case you want to get straight to the good stuff, here are the main reasons why you should be using SVGs if you’re not already.

7 Reasons Why You Should Be Using Scalable Vector Graphics

  1. SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
  2. SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
  3. Embedded SVGs can be styled using CSS.
  4. They are SEO friendly allowing you to add keywords, descriptions and links directly to the markup.
  5. SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility.
  6. They are future proof. SVGs can be scaled indefinitely meaning that they will always render to pixel-perfection on newer display technologies such as 8K and beyond.
  7. SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site.

What Is SVG and What Is SVG Used For?

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

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

In its simplest form, this is what an SVG file looks like under the hood:

 

<svg xmlns="http://www.w3.org/2000/svg">
  <rect width="250" height="250" fill="#0000FF"/>
</svg>

That SVG file would render a 250 pixels wide, blue square.

So how are SVGs different?

Well, traditional image types like JPEG, PNG and GIF are bitmap-based (or raster-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 supersede the JPEG, PNG and GIF file formats altogether as a singular more flexible solution. I feel as if discussing WebP would make this article more confusing than helpful as it’s a different subject altogether which I’d be happy to consider in another article.

In short, the WebP image type was created to generate much smaller file sizes and eliminate 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 or read this article by our very own Ian Jones which discusses WebP compression in a bit more detail as well as how to serve WebP images using WP Offload Media.

Right, back on track…

So how does the SVG format differ to bitmap-based images? They are vector-based meaning that they are resolution independent. Rather than consisting of pixels, SVG images consist 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 Awesome Advantages of SVGs

Pixel-Perfect Scaling!

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

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

pixel perfect scaling

Food for thought: Despite this fact, small SVGs that contain a little amount of detail such as a navigation bar icon may look out of place or too simplistic if blown up to be used on a storefront banner or a billboard. Every case is different, but context and a good eye is important when deciding whether to scale an SVG.

Smaller File Sizes

This is another substantial advantage. Due to the nature of vector images, 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 quantity 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 file will be more expensive than an SVG counterpart.

On top of this, you can minimize the size of your SVG files 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 Style 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 modification like a color change. In fact, if you’ve done any sort of web design or front-end development you’ll have no difficulties adding a gradient to a shape or increasing the thickness of a stroke.

style svgs using css

SEO Friendly

As I indicated at the start of this post, SVGs are XML-based signifying that keywords, descriptions and links can be included making the content more recognizable for search engines and improving overall accessibility.

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 advantageous?

It means that they can be searched and indexed which is great for accessibility. You can also modify 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 Future Proof

I think this is something that is considerably overlooked, particularly when it comes to scalability. 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 wonderful. But it meant that most of the JPEG or PNG images used on websites were not of a high enough resolution anymore and looked like garbage on handheld devices.

The solution? Generate 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 required 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 meant that this no longer created complications as high-end devices reach resolutions of 8K and beyond.

They Can Be Animated

This is where SVGs really excel. Having the ability to edit SVGs directly with a text editor means they can be animated, making it super easy to inject some interactivity into your site. These animations can be as simple or as complicated as you prefer. Similar to HTML, SVGs are also represented by the DOM (document object model) meaning that they can be manipulated with JavaScript too.

If you’re interested in animating SVGs, I covered this subject in another article along with a guide on how to use Airbnb’s popular Lottie animation framework to bring your SVGs to life.

Here’s an example animation I made for that particular article based on our branding for WP Migrate DB Pro.

 

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

 

 

The Disadvantages of SVG

Nothing is perfect. And there are a couple of instances where you should potentially opt for raster images over SVGs.

Complex Imagery

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

Similarly, there are some instances whereby a complicated SVG contains 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 a definite possibility.

If you need to use a bitmap image, remember to use PNG if your image contains transparency, JPEG if it does not. JPEG images do not support transparency and are therefore better suited to photographs. Alternatively, as 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 application such as Adobe Illustrator or Inkscape. Empty group folders and unused, redundant layers can append unnecessary junk to the overall file size. Additionally, older SVGs generally contain an abundance of garbage in the markup and are considerably more expensive than necessary. I run all my SVGs through a minifier when I export during the design process to avoid such complications.

There are several optimization tools out there including a Node.js tool for optimizing SVG files. And thank you to Jordan, who shared this non-node solution called SVGOMG in the comments.

SVGs can massively outweigh a counterpart PNG if not 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 double 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’re anti Chrome or Firefox, or need to support super outdated web browsers like Internet Explorer, then you may encounter some compatibility issues with SVG.

That being said, you can still use SVGs and avert this complication by implementing JPEG or PNG fallbacks as a failsafe.

SVG Icons Are Your Friend

Icons are where all of the advantages of this file format really become apparent. No longer are multiple icons in several colors and sizes required which massively 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 were 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 occasionally additional states too (such as a hover state).

As discussed previously, bitmap images are not editable using CSS so each icon state required its own file.

I also mentioned that when higher pixel density screens became a thing, we also had to generate 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 examine how much file size I could recoup using an icon set of SVGs over bitmap versions.

I have a heart SVG icon from the Material Design that I require 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 adjusting the CSS styling. So we only need one SVG file to generate all 3 icons!

 

 

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

Additionally, to guarantee the bitmap versions look sharp on all types of devices, we need to generate 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 single SVG file we can use to achieve identical results.

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

Sure, 29KB doesn’t sound considerable, but this is in reference to a single icon. If we had 30 icons to use, the difference in file size becomes more of a complication…

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 tremendous increase in size nonetheless.

svg vs png test result

I hope this has demonstrated just 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 PNGs. Particularly if you are optimizing your SVG icons and want them 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 have been using a neat SVG workflow to generate 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 assemble all 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 beginning of the <body> tag in our theme:

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

And hide the gigantic SVG with CSS, so it’s completely hidden until called 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 attached 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 amazing!

Where to Get Free SVG Icons

Here are several different sources that I use to acquire SVGs and icon sets. Some require you to credit the author depending on how the icon is utilized, so be conscious of that.

Flaticon
Material Design Icons
Icons8
FreeIcons
IconStore

Recap

Hopefully, by this point, I’ve presented considerable evidence as to why you should be thinking about using the SVG file type if you’re not already. They’re easier to manage, will improve the load speed of your web pages and won’t require an update every time a new resolution display splashes onto the market with a higher PPI (pixels per inch).

Additionally, you can animate and make modifications to the styling of your SVGs without needing or knowing how to use a design application like Photoshop or Sketch (Or CorelDRAW if you’re a vector OG).

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

This entry was posted in WP Migrate DB Pro, Side Hustle and tagged Development, svg, advantages, developers, icons, scalable, vector, graphics, jpeg, png, bitmap.

ABOUT THE AUTHOR

img

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.

@pixels4lyf lewiswarren.co.uk

https://css-tricks.com/using-svg/

SVG is an image format for vector graphics. It literally means Scalable Vector Graphics. Basically, what you work with in Adobe Illustrator. You can use SVG on the web pretty easily, but there is plenty you should know.

 

Why use SVG at all?

  • Small file sizes that compress well
  • Scales to any size without losing clarity (except very tiny)
  • Looks great on retina displays
  • Design control like interactivity and filters

Getting some SVG to work with

Design something in Adobe Illustrator. Here’s a Kiwi bird standing on an oval.

img

Notice the artboard is cropped up right against the edges of the design. Canvas matters in SVG just like it would in PNG or JPG.

You can save the file directly from Adobe Illustrator as an SVG file.

img

As you save it, you’ll get another dialog for SVG Options. I honestly don’t know much about all this. There is a whole spec for SVG Profiles. I find SVG 1.1 works fine.

img

The interesting part here is that you can either press OK and save the file, or press “SVG Code…” and it will open TextEdit (on a Mac anyway) with the SVG code in it.

img

Both can be useful.

Using SVG as an

If I save the SVG to a file, I can use it directly in an <img> tag.

<img src="kiwi.svg" alt="Kiwi standing on oval">

In Illustrator, our artboard was 612px ✕ 502px.

img

That’s exactly how big the image will on the page, left to itself. You can change the size of it though just by selecting the img and changing its width or height, again like you could a PNG or JPG. Here’s an example of that:

Browser support

Using it this way has its own set of specific browser support. Essentially: it works everywhere except IE 8 and down and Android 2.3 and down.

If you’d like to use SVG, but also need to support these browsers that don’t support using SVG in this way, you have options. I’ve covered different techniques in different workshops I’ve done.

One way is to test for support with Modernizr and swap out the src of the image:

if (!Modernizr.svg) {
  $(".logo img").attr("src", "images/logo.png");
}

David Bushell has a really simple alternative, if you’re OK with JavaScript in the markup:

<img src="image.svg" onerror="this.onerror=null; this.src='image.png'">

SVGeezy can also help. We’ll cover more fallback techniques as this article progresses.

Using SVG as a background-image

Similarly easy to using SVG as an img, you can use it in CSS as a background-image.

<a href="/" class="logo">
  Kiwi Corp
</a>
.logo {
  display: block;
  text-indent: -9999px;
  width: 100px;
  height: 82px;
  background: url(kiwi.svg);
  background-size: 100px 82px;
}

Notice we set the background-size to the size of the logo element. We have to do that otherwise we’ll just see a bit of the upper left of our much larger original SVG image. These numbers are aspect-ratio aware of the original size. But you could use a background-size keywords like contain if you want to make sure the image will fit and can’t know the parent image will be of the exact right size.

Browser support

Using SVG as background-image has its own special set of browser support, but it’s essentially the same as using SVG as img. The only problem browsers are IE 8 and down and Android 2.3 and down.

Modernizr can help us here, and in a more efficient way than using img. If we replace the background-image with a supported format, only one HTTP request will be made instead of two. Modernizr adds a class name of “no-svg” to the html element if it doesn’t support SVG, so we use that:

.main-header {
  background: url(logo.svg) no-repeat top left;
  background-size: contain;
}

.no-svg .main-header {
  background-image: url(logo.png);
}

Another clever progressive enhancement flavored technique for using SVG as background-image is by using it in conjunction with multiple backgrounds. SVG and multiple backgrounds have very similar browser support, so if the browser supports multiple backgrounds, it supports SVG, and the declaration will work (and override any previous declaration).

body {
  background: url(fallback.png);
  background-image: url(image.svg), none;
}

The problem with both and background-image…

Is that you don’t get to control the innards of the SVG with CSS like you can with the following two ways. Read on!

Using “inline” SVG

Remember how you can grab the SVG code right from Illustrator while saving if you want? (You can also just open the SVG file in a text editor and grab that code.) You can drop that code right into an HTML document and the SVG image will show up just the same as if you put it in an img.

<body>

   <!-- paste in SVG code, image shows up!  -->

</body>

This can be nice because the image comes over right in the document and doesn’t need to make an additional HTTP request. In other words, it has the same advantages as using a Data URI. It has the same disadvantages too. A potentially “bloated” document, a big chunk of crap right in the document you’re trying to author, and inability to cache.

If you’re using a back end language that can go fetch the file and insert it, at least you can clean up the authoring experience. Like:

<?php echo file_get_contents("kiwi.svg"); ?>

A little PHP-specific thing here… it was demonstrated to me that file_get_contents() is the correct function here, not include() or include_once() as I have used before. Specifically because SVG sometimes is exported with <?xml version="1.0" encoding="UTF-8"?> that as the opening line, which will cause the PHP parser to choke on it.

Optimize it first

Likely not a huge shocker, but the SVG that Adobe Illustrator gives you isn’t particularly optimized. It has a DOCTYPE and generator notes and all that junk. SVG is already pretty small, but why not do all we can? Peter Collingridge has an online SVG Optimiser tool. Upload the old, download the new. In Kyle Foster’s video, he even takes it the extra mile and removes line breaks after this optimization.

If you’re even more hardcore, here is a Node JS tool for doing it yourself.

Now you can control with CSS!

See how the SVG looks a lot like HTML? That’s because they are both essentially XML (named tags with angle brackets with stuff inside). In our design, we have two elements that make up the design, an <ellipse> and an <path>. We can jump into the code and give them class names, just like any other HTML element can have.

<svg ...>
  <ellipse class="ground" .../>
  <path class="kiwi" .../>
</svg>

Now in any CSS on this page we can control those individual elements with special SVG CSS. This doesn’t have to be CSS embedded in the SVG itself, it can be anywhere, even in our global stylesheet <link>ed up. Note that SVG elements have a special set of CSS properties that work on them. For instance, it’s not background-color, it’s fill. You can use normal stuff like :hover though.

.kiwi {
  fill: #94d31b; 
}
.kiwi:hover {
  fill: #ace63c; 
}

Even cooler, SVG has all these fancy filters. For instance blurring. Chuck a filter in your <svg>:

<svg ...>
  ...
  <filter id="pictureFilter" >
    <feGaussianBlur stdDeviation="5" />
  </filter> 
</svg>

Then you can apply that in your CSS as needed:

.ground:hover {
  filter: url(#pictureFilter);
}

Here’s an example of all that:

Browser support

Inline SVG has it’s own set of browser support, but again, it’s essentially only an issue in IE 8 and down and Android 2.3 and down1.

One way to handle fallbacks for this type of SVG is:

<svg> ... </svg>
<div class="fallback"></div>

Then use Modernizr again:

.fallback { 
  display: none;
  /* Make sure it's the same size as the SVG takes up */
}
.no-svg .fallback { 
  background-image: url(logo.png); 
}

Using SVG as an

If “inline” SVG just isn’t your jam (remember it does have some legit drawbacks like being hard to cache), you can link to an SVG file and retain the ability to affect its parts with CSS by using <object>.

<object type="image/svg+xml" data="kiwi.svg" class="logo">
  Kiwi Logo <!-- fallback image in CSS -->
</object>

For the fallback, Modernizr detection will work fine here:

.no-svg .logo {
  width: 200px;
  height: 164px;
  background-image: url(kiwi.png);
}

This will work great with caching and actually has deeper support than using it any other way. But, if you want the CSS stuff to work, you can’t use an external stylesheet or <style> on the document, you need to use a <style> element inside the SVG file itself.

<svg ...>
  <style>
    /* SVG specific fancy CSS styling here */
  </style>
  ...
</svg>

External stylesheets for SVG

SVG has a way to declare an external stylesheet, which can be nice for authoring and caching and whatnot. This only works with <object> embedding of SVG files as far as I’ve tested. You’ll need to put this in the SVG file above the opening <svg> tag.

<?xml-stylesheet type="text/css" href="svg.css" ?>

If you put that in your HTML, the page will barf and not even try to render. If you link up an SVG file that has that in it as an <img> or background-image, it won’t barf, but it won’t work (the SVG will still render though).

Data URL’s for SVG

Another way to use SVG’s is to convert them into Data URL’s. Data URL’s might not save you actual file size, but can be more efficient because the data is right there. It doesn’t require an additional network request.

Mobilefish.com has an online conversion tool for that base64ing them, but I generally don’t think that’s a good idea for SVG. Simply paste in the contents of your SVG file and fill out the form and it will display the results in a textarea for you to copy. Remember to remove line breaks in the data it gives you back. It looks like pure gibberish:

img

You can use that anywhere we’ve talked about so far (except inline <svg> because that just doesn’t make sense) Just put the gibberish where it says [data] in these examples.

This converter is my fav, as it leaves the SVG as mostly readable text:

 

As

<img src="data:image/svg+xml;base64,[data]">

As CSS

.logo {
  background: url("data:image/svg+xml;base64,[data]");
}

Relevant note here: regular CSS doesn’t care if you put quotes around the data URI, but Sass does, so I’ve quoted it above (Thx Oziel Perez).

As
<object type="image/svg+xml" data="data:image/svg+xml;base64,[data]">
  fallback
</object>

And yep, if you have an embedded <style> in your SVG before you base64 it, it will work if you use it as an <object> still!

Format for Data URI

All the examples above have base64 as the encoding, but data URI’s do not have to be base64. In fact in the case of SVG, it’s probably better NOT to use base64. Primarily because the native format of SVG is much more repetitive than base64 ends up, it gzips better.

<!-- base64 -->
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL...

<!-- UTF-8, not encoded -->
data:image/svg+xml;charset=UTF-8,<svg ...> ... </svg>

<!-- UTF-8, optimized encoding for compatibility -->
data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://...'

<!-- Fully URL encoded ASCII -->
data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A//...

Command line thingy for base64ing SVG:

Or alternatively Mathias Bynens has some techniques:

Use openssl base64 < path/to/file.png | tr -d '\n' | pbcopy or cat path/to/file.png | openssl base64 | tr -d '\n' | pbcopy to skip writing to a file and just copy the base64-encoded output to the clipboard without the line breaks.

And a drag-and-drop tool.

Automation Tools

  • grunticon

    :

    From a CSS perspective, it’s easy to use, as it generates a class referencing each icon, and doesn’t use CSS sprites.

    grunticon takes a folder of SVG/PNG files (typically, icons that you’ve drawn in an application like Adobe Illustrator), and outputs them to CSS in 3 formats: svg data urls, png data urls, and a third fallback CSS file with references to regular png images, which are also automatically generated and placed in a folder.

  • iconizr

    :

    A PHP command line tool for converting SVG images to a set of CSS icons (SVG & PNG, single icons and / or CSS sprites) with support for image optimization and Sass output.

Kyle Foster’s An Optimized SVG Workflow, which is worth an embed:

 

 

… and the follow up + slides.


1 And speaking of Android 2.3 browser, this. But if you absolutely have to support the native browser, this.

More?

Scroll to Top