How to: SVG CSS backgrounds

Optimizing graphics is a high-priority task when decreasing site loeading time, since images account for over 90 % of data.

This post should help you getting started with creating vector images from scratch or via conversion from other formats, optimizing for better efficiency, tackling some compatibility issues and includes links to worthwhile resources.

Since Scalable Vector Graphics provides unmatched data volume / visual quality in many cases, using it is a good idea for virtually any site.

Raster formats vs vector images

Raster formats all take a slightly different approach to describing colours of pixels in a grid.

SVG-vs-bitmap

A basic bitmap (BMP) does just that. Other formats (JPG, GIF..) take an original bitmap and optimize the data in some way. That means discarding unnecessary information (lossless formats) or often sacrificing image data, thus quality (lossy formats).

SVG, on the other hand, can be seen as a set of instructions on how to create the wanted image.

SVG

A simple example - raster

To oversimplify, imagine this situation:

If you zoom in on pixels of a raster image, most neighbouring pixels are the same, or almost the same colour. Knowing this, we can discard information about some of these. E.g. if there are three pixels in a row, where the 1st and 3rd one are both red, there is a good chance the 2nd is also red.
Should the 3rd one be yellow, it is likely for the 2nd to be orange. To reduce the filesize of this image by half, simply discard information about every second pixel and have an algorithm compute it back, based on adjacent pixels, when the image is being rendered. Not all of the image consists of gradients, so this approach would result in softening edges, or unwanted blurring. Of course, real-world raster image compression is much more complicated, but the image always contains more or less accurate data of the final image.

A simple example - SVG

If an SVG image is defined as "a square made of two same-sized rectangles, where the top one is red and bottom one white", there is the instructions for the national Flag of Monaco* in full. This is much more efficient then describing each of the pixels using a raster format (red, red, red... white, white, white), no matter how well optimized.

A great benefit of this flag's description is, that it lets you draw a final image in perfect quality regardless of size/scale and type of display, whereas the number of pixels is always limited.

Again, the language of vector graphics is in essence math, and is more complicated then in this example, it allows for far more complex images to be drawn, but allows the source file to be read and edited directly.

*The Flag of Monaco is not really square, but pretty close.

More on this: https://vector-conversions.com/vectorizing/raster_vs_vector.html

Real-world use of SVG

There are tens of image formats, all have a purpose, strengths and weaknesses. JPG and PNG are ideal for photographs. GIF is efficient where limited number of colors will suffice and scalability is not required. It allow animations.

On the web, SVG (Scalable Vector Graphics) is ideal for icons. Using shapes, paths (mathematically described lines/curves) and others, the objects are drawn.

Icons, logos, drawings - SVG vs other formats

The following example shows Facebook logo drawn using SVG, GIF, PNG and JPG, where the PNG image is officialy the source from Facebook Resource Center. Notice the JPG artifacts in the last and largest sample.

Format Bytes Image Top right corner
SVG 376 SVG SVG
GIF 1 751 SVG-vs-GIF SVG-vs-GIF
PNG 2 179 SVG-vs-PNG SVG-vs-PNG
JPG 13 515 SVG-vs-JPG SVG-vs-JPG

Contents of the SVG file "describing" the Facebook logo above, as visible in a text editor:

<svg xmlns="http://www.w3.org/2000/svg" version="1" viewBox="0 0 144 144"><path fill="#3b579d" d="M7 0h130c4 1 6 3 7 7v130c-1 4-3 6-7 7H99V88h19l3-21H99V49c1-4 4-6 7-7h16V22c-10-1-21-3-31 2-8 4-13 12-14 21v22H58v21h19v56H7c-4-1-6-3-7-7V7c1-4 3-6 7-7z"/><path fill="#fff" d="M91 24c10-5 21-3 31-2v20h-16c-3 1-6 3-7 7v18h22l-3 21H99v56H77V88H58V67h19V45c1-9 6-17 14-21z"/></svg>

A photograph - SVG vs other formats

Format Bytes Image Top right corner
SVG 28 775 SVG SVG
GIF 7 182 SVG-vs-GIF SVG-vs-GIF
PNG 9 797 SVG-vs-PNG SVG-vs-PNG
JPG 9 794 SVG-vs-JPG SVG-vs-JPG

These two examples show that main application of vector graphics is drawing simple shapes or objects, which consist of them. Even though SVG can do gradients, patterns, clipping, masking, transparency, text, interactivity, animations to create a lot of pretty cool stuff, it fails to contain real-world imagery. Or even fiction, as seen above. :)

Designing custom SVGs

Creating SVG from scratch allows you to get the exact required result. Typical tools for designing vectors are, in no particular order:

Editor Review License Comment
Vectr thenextweb.com Free Intuitive, for beginners, collaboration feats.
Inkscape lifewire.com Free For long-term-ish use, or professionals.
Gravit medium.com Free Cross-platform (app and browser), in the cloud tool
BoxySVG sitepoint.com Free trial ($9.99) In-depth, cross-platform, aimed at online efficiency
Adobe Illustrator creativebloq.com Free trial ($29.99/mo) A traditional tool, over 30 years on the market, part of a graphics suite
Google Drawings slant.co Free A basic shape editor, that can export to SVG, in the cloud - part of Google Docs

Converting to SVG

In most cases of more complex graphics, creating from scratch leaves you with no more, or less, then the desired result. Conversion from other formats is guesswork on side of software.

Googling "convert to svg" will get you a pretty good selection of online and downloadable tools to get SVG from other formats.

One worth recommending is Vector Magic - while it is not free, it outsmarts most other tools and lets you fool around with the following settings and preview the output during the conversion process, before the final image is saved:

  • Number of segments and their size
  • Anti-alias handling to prevent recreation of artifacts
  • Color clustering (combining similar colors)
  • Editing the SVG (combining splitting and erasing segments by actually drawing, erasing and filling into the SVG MS Paint-like)
  • Level of smoothness, corner detection, number of nodes, removing background fills

vectormagic

SVG resources

Site Comment
icons8.com - 10 000s free flat icons Many formats, adjust size and colors before download.
freepik.com - Almost 100 000 free icons Free icons for personal and commercial use. Download PNG, EPS and SVG.
A neat online icon designer Part of iconfinder.com - search through over 2 000 0000 SVG icons.
IcoMoon App An online app to generate SVG icon sets and fonts.
awwwards.com - best SVG websites Sites using (some of) SVG graphics.

Optimize SVG using SVGO

When you create your own vector graphics, the editor will output exactly what you have asked it to, which is likely to by more the you actually need. You can settle for a much lower level of detail and accuracy with for-web-SVGs, then would be required for technical blueprints.

Creating custom SVG efficiently is beyond the scope of this post, but a good reading on this can be found on css-tricks.com. This may not be your cup of tea, but you should still pay attention to the subject of optimization when implementing existing graphics, since optimizing it can dramatically reduce the size dramatically. Reducing downloaded SVG kit down to 20% of original size is often possible.

Probably the best tool out there is SVGO (SVG Optimizer) - a Node.js-based tool for optimizing SVG files. You will probably find yourself using SVGOMG! (SVGO's Missing GUI), which is the online version ov the above, free and easy to use.

SVGOMG! allows you to set 43 options, but is pretty much good to go as it is. After every change of settings, the output code and is size is provided, so you can play around with the settings.

SVGOMG

SVG in CSS

Benefits

Users who want to save bandwidth or increase speed of browsing might disable images in their browser. Having the CSSed SVG can ensure icons showing up even with images disabled in browser, which is a good idea, since the negative impact on saving bandwidth and increasing speed is very little, and you want to provide the visitor with at least the basic navigation set. Images in the form of CSS data URIs will be visible, since image blockers might not take them into account and they could still be used by the browser.

All images in a single stylesheet need less HTTP requests when being downloaded by the browser. This results in less overhead data and server-client roundtrips, because each of the image files would otherwise need to be dowloaded separately.

Images in a single file allow more efficient compression.

Compatibility issues

SVG in CSS backgrounds are supported by over 95% of browsers. However, there are issues that need to be addressed in case of Firefox and Internet Explorer, specifically, escaping and character encoding. The following Codepen demo let's you view their (non-)working combinations in different environments:

See the Pen Compatibility issues of SVG in CSS data URIs by Martin Korvas (@Marko36) on CodePen.

Requirements for URL encoding and definition of charset have been tested on:

  • Internet Explorer 9, 10, 11 on Windows 7, 8, 10
  • Chrome 36 and 50 on Windows 10 and OS X Mavericks
  • Firefox 45 on Windows 10
  • Safari on iPhone 5S, iPhone 6 Plus, iPad 4th gen
  • Samsung Galaxy Tab 4, Galaxy S5
  • Google Nexus

The results are as follows:

IE needs charset to be defined in full or not at all, as it does not accept shorthand.
background: url('data:image/svg+xml,utf8...
background: url('data:image/svg+xml;charset=utf-8...
background: url('data:image/svg+xml,...

IE and Firefox need the SVG data to be escaped (URLendcoded).
background: url('data:image/svg+xml,<svg xmlns="http...
background: url('data:image/svg+xml,%3Csvg%20xmlns%3D%22http...

Good news is, that none of the setups required spaces to be replaced by (encoded to) %20, which saves up space.

SVGMagic: JQuery fallback plug-in

To fail-safe your site against SVG compatibility issues you can go with Dirk Groenen's SVGMagic - a JQuery plug-in, which provides a fallback in case the client does not support SVG.

Make it work in two simple steps:

  • Download and inlude the jquery.svgmagic.js script
  • Initialize it within your page. The code is quite simple:

$(document).ready(function(){ $('img').svgmagic(); });

This hack is somewhat quick but dirty, since it requires the end device to actually transcode image files.

Iconizr: CSS icon kit creator with fallback

Iconizr by Joschi Kuphal is a free tool, which takes your SVG icons (up to 50 at once, max. 300kB each) and returns a CSS kit for your site.

SVG Iconizr

With the deault setup, you get:

  • a CSS stylesheet with your icons in URLencoded data URIs as background in rules with their respective names.
  • an SVG sprite (all icons combined into a single image), and a CSS with classes that load and position it.
  • the above two outputs, but using PNG instead of SVG, to resolve compatibility issues.

Besides CSS, you can also get Sass, and tweak some additional options. To avoid limitations of the drag&drop browser version, you can install a desktop one.