Resolution Independence With SVG

Advertisement

In this article, we’ll look at Scalable Vector Graphics (SVG), one of the most underused technologies in website development today.

Before diving into an example, let’s consider the state of the Web at present and where it is going. Website design has found new vigor in recent years, with the evolving technique of responsive design. And for good reason: essentially, responsive website design moves us away from the fixed-width pages we’ve grown accustomed to, replacing them with shape-shifting layouts and intelligent reflowing of content. Add to that a thoughtful content strategy and mobile-first approach, and we’re starting to offer an experience that adapts across devices and browsers to suit the user’s context.

When we look at the breadth of Web-enabled devices, responsive design is sure to provide a better user experience. Scrolling horizontally, panning and zooming the viewport have their place in user interface design, but forcing the user to do these things just to navigate a website quickly becomes tedious. Fitting the website to the viewport is about more than just layout: it’s also about resolution. In this article, I’ll demonstrate why SVG is a perfect addition to future-friendly Web development.

Introducing SVG

SVG offers a truly resolution-independent technique for presenting graphics on the Web. SVG is a vector graphics format that uses XML to define basic properties such as paths, shapes, fonts and colors, and more advanced features such as gradients, filters, scripting and animation. Create the file once and use it anywhere, at any scale and resolution.

Consider the use cases: UI and navigation icons, vector-style illustrations, patterns and repeating backgrounds. For all of these, a scalable graphic is the perfect solution from a visual standpoint, and yet fixed-resolution images are still the norm. In the example below, we’ll show you how to expand on a common development technique to take advantage of SVG.

Resolution independence with SVG

A Case Study: CSS Sprites

We all know about the CSS sprites technique. (If you don’t, then have a quick read through Sven Lennartz’ article1. And Louis Lazaris points out its pros and cons2.) In the example below, we’ll show how seamlessly SVG replaces normal raster images. If this technique is not for you, you can certainly imagine a whole array of similar situations in which to use SVG.

Vector icons play a big role in user interface design. Pictures express concepts with vivid clarity, whereas their textual counterparts might carry ambiguity. In UI design, where space is scarce, a simple illustrated icon could be greatly welcome.

I’ve mocked up the following example:

An icon based UI menu

I’ll be first to admit that this row of icons won’t win any design awards, but it will suffice for the sake of this article! Let’s look at the HTML:

<div class="actions">
   <a class="a-share" href="#">Share</a>
   <a class="a-print" href="#">Print</a>
   <a class="a-tag" href="#">Tag</a>
   <a class="a-delete" href="#">Delete</a>
</div>

I’ve kept the HTML to a minimum for clarity, but in practice you’d probably want to mark it up with an unordered list. And you’ll almost certainly want to replace those hashes with real URLs (even if JavaScript provides the functionality, having a fallback is nice). Let’s look at the CSS:

.actions {
   display: block;
   overflow: auto;
}

.actions a {
   background-image: url('sprite.png');
   background-repeat: no-repeat;
   background-color: #ccc;
   border-radius: 5px;
   display: block;
   float: left;
   color: #444;
   font-size: 16px;
   font-weight: bold;
   line-height: 20px;
   text-decoration: none;
   text-shadow: 0 -1px 2px #fff;
   padding: 10px 20px 10px 40px;
   margin-right: 5px;
}

.a-share  { background-position: 10px 0; }
.a-print  { background-position: 10px -40px; }
.a-tag    { background-position: 10px -80px; }
.a-delete { background-position: 10px -120px; }

Note the fixed-pixel sizing and the PNG background, which we can see below framed in full Photoshop production glory:

A PNG sprite in Photoshop

This implementation of a CSS sprite is basic, and at today’s standard, it’s not good enough! How can we enhance this? First, let’s consider the following issues:

  1. We’ve rasterized the image at a very early stage. Even at full size, icons in which points sit between pixels, such as the one for “Print,” have blurred.
  2. If we zoom in, the image will blur or pixellate even more; there is no additional data to re-render the image at larger sizes.
  3. Everything has a fixed size, which is neither good for responsive design nor good for accessibility, because the browser’s default font size is ignored.

As you’ve probably guessed by now, we’ll show you how SVG solves these problems. But first, let’s reiterate each point thoroughly to understand the issues at large.

1. Rasterization

Devices such as modern smartphones have a very high pixel density; some already surpass the 300 pixels-per-inch (PPI) mark that is assumed to be the limit of the human eye’s ability to distinguish fine details. A pixel has no real-world equivalent in size until it sits on a screen of fixed dimension (say, 3.5 inches diagonally) and fixed resolution (say, 640 × 960 pixels). At this scale, text with a font size of 16 pixels would be incredibly small to the eye. For this reason, devices simply cannot translate 1 CSS pixel unit to 1 device pixel; instead, they double up. Thus, a 16-pixel font size actually takes over 32 pixels when rendered.

The same applies to images; but they are already rasterized, so doubling up the pixels has no benefit. In our example, each icon has been rasterized at around 25 × 25 pixels (the whole sprite being 30 × 160), so they cannot take advantage of the double pixel ratio. One solution is to use CSS media queries to detect the pixel ratio. This is already implemented in Webkit- and Gecko3-based browsers.

To improve our example, we can add the following CSS declaration:

@media only screen and (-webkit-min-device-pixel-ratio: 2)  {
   .actions a {
      background-image: url('sprite@2x.png');
      background-size: 30px 160px;
   }
}

The alternate background image supplied in the code above has been saved at 60 × 320 pixels (i.e. double the original dimensions). The background-size property tells CSS to treat it smaller. Significantly, now the device has the additional data to render a better image (if capable).

This solution isn’t bad, but it doesn’t solve the problems we’ll run into in points 2 and 3 below. It also requires that we maintain multiple files of increasing size: a potential burden on bandwidth and a real hassle. For non-vector images, such as photography in JPG format, we can’t do much more than that.

2. Zooming

At their default size, our rasterized icons look acceptable, at least on low-pixel-density screens. However, should the user zoom in on the Web page, these little UI delights will degrade very quickly.

A PNG sprite zoomed in and blurred.

Zooming is a common action when users find a website too small for comfortable viewing. Or, to put it another way, websites that are designed too small are very common. There is really no “perfect” size, because almost everyone has at least some level of visual impairment, since our eyes inevitably deteriorate with age. Secondly, with the rapid increase in touchscreen devices, pinch-to-zoom has become the standard way to enlarge fixed-sized content designed for larger screens (i.e. much of the Web today).

We should develop websites in a way that minimizes the need for user input — that’s where responsive design comes in (see point 3 below) — but zooming is here to stay. There’s simply no way to provide pre-rasterized images for every level of zoom (in theory, an infinite scale). Scalable graphics are the solution, and we’ll show you how to enhance our example. But first, a related word on fixed sizing.

3. Fixed Sizes

Presenting page elements at fixed sizes forces many users to zoom, but it also disables a very useful browser feature. Users can set their preferred font size (the default in browsers is 16 pixels). By sizing everything in pixels, we override this preference. Sizing elements based on this default is much better, so that, if the text is bigger, everything adjusts to match. This essentially mimics the zooming effect but happens without the user having to manually do it on every visit. Ethan Marcotte has written a great article that explains relative font sizes4.

Let’s re-implement our sprite example with a solution to these three issues.

A Scalable Implementation

Here is the HTML again. We don’t need to change anything here.

<div class="actions">
   <a class="a-share" href="#">Share</a>
   <a class="a-print" href="#">Print</a>
   <a class="a-tag" href="#">Tag</a>
   <a class="a-delete" href="#">Delete</a>
</div>

The updated CSS is where the magic happens:

body { font-size: 100%; }

.actions {
   display: block;
   overflow: auto;
}

.actions a {
   font-size: 1em;
   line-height: 1.25em;
   padding: 0.625em 1.25em 0.625em 2.5em;
   margin-right: 0.3125em;
   border-radius: 0.3125em;
   background-image: url('sprite.svg');
   -webkit-background-size: 1.875em 10em;
   -o-background-size: 1.875em 10em;
   -moz-background-size: 1.875em 10em;
   background-size: 1.875em 10em;
   /* styles carried over from the original implementation */
   background-repeat: no-repeat;
   background-color: #ccc;
   color: #444;
   display: block;
   float: left;
   text-decoration: none;
   text-shadow: 0 -1px 2px #fff;
}

.actions-em .a-share { background-position: 0.625em 0; }
.actions-em .a-print { background-position: 0.625em -2.5em;  }
.actions-em .a-tag { background-position: 0.625em -5.0em;  }
.actions-em .a-delete { background-position: 0.625em -7.5em;  }

In this version, we’ve made the following changes:

  • The background-image is now an SVG file.
  • All sizes are based on the default of 16 pixels, or 1 em. If the user’s default is larger or smaller, then everything will scale relatively. (If you multiple each em size by 16, you’ll get the number of pixels used in our initial fixed-size example.)
  • The background-size is very important. By setting this in em units, we’re telling the browser to scale the sprite relative to everything else. You’ll notice that 1.875 × 10 em multiplied by 16 becomes 30 × 160 — the base size at which we produced the sprite in pixels.
  • The background-position of each sprited icon is also based on relative units.

Now that we’re using SVG and relative sizes, we have solved the three big issues highlighted above. A scalable graphic can be rasterized on demand to perfectly suit any device resolution and any zoom level. By using relative sizes, we can continue implementing a responsive design, minimizing as much as possible the need for the user to zoom. We’re also respecting the browser’s default font size, and enabling our design to adapt accordingly.

I actually produced the SVG sprite first and the PNG version from that. (I imported the SVG in Photoshop before exporting it as a PNG — Illustrator’s PNG export had very poor rasterization.) Below is the header in my SVG file. Notice the same 30 × 160 initial size.

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   width="30px" height="160px" viewBox="0 0 30 160" enable-background="new 0 0 30 160" xml:space="preserve">

You can see that the attributes for width and height are set in pixels (width="30px" height="160px") in the opening svg tag (as generated by Adobe Illustrator). This actually causes it to render early in Firefox, before the graphic has scaled to match the em sizes in background-size. Webkit-based browsers seem to scale the SVG perfectly, regardless. I’ve found that editing the SVG file to use em units in these two attributes fixes any rendering issues in Firefox.

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   width="30em" height="160em" viewBox="0 0 30 160" enable-background="new 0 0 30 160" xml:space="preserve">

I don’t know which browser actually implements this scaling correctly, but let it be noted that extra care is needed to ensure cross-browser perfection. Mozilla MDN has an excellent in-depth article, “Scaling of SVG Backgrounds5,” which explores more practical examples. For more ideas, see Alex Walker’s article “A Farewell to CSS3 Gradients6.”

Here’s a super-close screenshot showing the SVG sprite:

A close-up of a SVG sprite.

The sprite scales beautifully. (Sadly, the same can’t be said for my tacky text-shadow effect.)

It’s best to experience the joys of scalable graphics and relative sizing firsthand. I’ve uploaded a side-by-side live demo7 demonstrating a combination of all the techniques mentioned above.

Browser Support

At the start of this article, I said that SVG was underused. I believe that has generally been the case due to poor browser support. But things are different now! Browser support for SVG has blossomed over the last year to the point where implementing it is a viable use of development time.

According to the website When Can I Use?8, support for SVG across multiple implementations is as follows (I’ve combined support for both CSS’ background-image and HTML’s img source — the most useful attributes):

  • Internet Explorer 9+
  • Firefox 4+
  • Chrome 4+
  • Safari 4+
  • Opera 9.5+

Mobile browser support9 is also pretty much across the board. If a workable fallback exists for older browsers, then SVG is a very viable solution.

For some of the new additions to Web standards, we can implement them safe in the knowledge that old browsers will simply ignore them and that they aren’t even required. We call this “progressive enhancement”: better browsers get a progressively better experience. SVG is slightly different, because for most practical purposes, it simply replaces other images in CSS backgrounds and HTML elements. The image format — be it SVG, PNG, JPG or GIF — is either supported or it isn’t. We can’t simply follow the practice of progressive enhancement here, because an image failing to render is not an acceptable experience.

Browser Sniffing or Feature Detection?

We could make an educated guess and say that we need to worry only about users of Internet Explorer 6 to 8. In this case, the conditional comments technique10 for IE-only styles enable us to re-apply a second CSS background-image of a supported format such as PNG, instead of the default SVG background.

Browsing sniffing is always a dangerous game. While Internet Explorer tends to be the main offender, we can never assume it is the only one.

The safer and highly recommended option is to detect SVG support and use it only if it’s found. I suggest using Modernizr11 if you need to detect multiple features. Modernizr applies a class of svg to your root html element if detected (to which you can apply SVG as a background-image). If you’re using SVG as the source of an image element in HTML, then implementation is a little harder. You’ll have to write more JavaScript to find and replace all sources once support has been established.

The problem with these methods is that the browser will download the fallback image before SVG is detected — the only exception being the conditional comments technique for IE. Users will also likely see a flash of re-styled content when the source image changes. This shouldn’t be the case for long; but at least for now, these problems may be enough to hold you off on SVG usage.

File Size

In our sprite example, the raw SVG file was 2445 bytes. The PNG version was only 1064 bytes, and the double-sized PNG for double-pixel ratio devices was 1932 bytes. On first appearance, the vector file loses on all accounts, but for larger images, the raster version more quickly escalates in size.

SVG files are also human-readable due to being in XML format. They generally comprise a very limited range of characters, which means they can be heavily Gzip-compressed when sent over HTTP. This means that the actual download size is many times smaller than the raw file — easily beyond 30%, probably a lot more. Raster image formats such as PNG and JPG are already compressed to their fullest extent.

Performance

Rendering performance is a concern with SVG, especially on mobile devices, whose hardware is limited. Raster images can be rendered pixel for pixel after decompression and de-encoding. Vector graphics need to be rasterized at a specific resolution every time they’re viewed.

SVG has consistently12 proved13 slower14 than Canvas as a platform for animating vector graphics; but our concern here is basic rendering, not manipulation a thousand times per second, and if that is possible, then simple rendering shouldn’t be a concern. The more intensive SVG features are things like clipping masks and filter effects. These are unnecessary for many practical purposes (like our sprite example), but, if required, the best way to check performance is by testing. A lot of Web development is supported in theory, but in practice results are far from perfect.

Alternative Methods

Hopefully you agree that SVG is extremely useful but not always the ideal solution to resolution independence. Ultimately, the trick is to avoid raster images while maintaining the scalability of visual styles. Below are a few more ideas to think about.

CSS3

You’ve probably already started combining CSS3 properties such as linear-gradient, text-shadow and box-shadow to create more complex styles. Web developer Lea Verou curates a CSS3 pattern gallery15 that shows off the impressive potential of gradients alone.

CSS3 gradient patterns16

In his article “Mobile Web in High Resolution17,” Brad Birdsall introduces a technique to maintain pixel perfection for high-resolution displays using the pixel-ratio property.

Then there are pure CSS “icons,” which Faruk Ateş18 rightly points out as being absolute “madness” — certainly so if you’re using CSS to create a logo! But you could argue the benefits of a small handful of very specific techniques, such as CSS triangles, as demoed by Chris Coyier19.

Web Fonts

Dingbat Web fonts20 and look-a-like Unicode glyphs are two interesting alternatives for vector icons, both with accessibility and semantic challenges. Jon Hicks has a write-up21 of perhaps the best practice for this. SVG seems a more appropriate technique for icons, but both have an immediate visual impact at high resolutions — and we’ll be paying increasing attention to that in coming years.

Looking Forward

As you can see, SVG usage is very much a possibility, and browser support and performance will only improve in future. What’s important to note from this article is that we really should be building websites that are as resolution-independent as possible.

Consider the “one Web” philosophy and the vast range of devices we use to access it — there is no single user experience. The more we can do to stay device-agnostic, the better. Responsive website design addresses many of these needs and certainly provides many benefits. Using vector graphics may not be as apparent, but its little improvements really do make a difference.

With today’s level of support, many users can experience the beauty of crisp scalable graphics… or perhaps that’s the wrong way to think about it. Most users won’t say “Wow! Kudos on the vectors.” To our dismay, they probably wouldn’t even consider them (and certainly wouldn’t recognize the effort required to craft them). And that’s a good thing; each time we improve the user’s experience, we don’t necessarily need to make a song and dance about it. Letting things continue to grind away under-appreciated is OK. It’s the lack of such things that gets recognized and sniffed at. Raise the user’s expectations in visual aesthetics, and they’ll start to notice the websites that do look shoddy. If you don’t do it, others will.

(al)

Footnotes

  1. 1 http://coding.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/
  2. 2 http://coding.smashingmagazine.com/2010/03/26/css-sprites-useful-technique-or-potential-nuisance/
  3. 3 https://developer.mozilla.org/en/CSS/Media_queries#-moz-device-pixel-ratio
  4. 4 http://blog.typekit.com/2011/11/09/type-study-sizing-the-legible-letter/
  5. 5 https://developer.mozilla.org/en/CSS/Scaling_of_SVG_backgrounds
  6. 6 http://designfestival.com/a-farewell-to-css3-gradients/A%20Farewell%20to%20CSS3%20Gradients
  7. 7 http://dbushell.com/demos/css-sprites/
  8. 8 http://caniuse.com/#search=SVG
  9. 9 http://mobilehtml5.org/
  10. 10 http://html5boilerplate.com/docs/The-markup/#ie-html-tag-classes
  11. 11 http://www.modernizr.com/
  12. 12 http://blogs.msdn.com/b/ie/archive/2011/03/08/comparing-hardware-accelerated-svg-across-browsers-with-santa-s-workshop.aspx
  13. 13 http://joeloughton.com/blog/web-applications/svg-vs-canvas-performance/
  14. 14 http://smus.com/canvas-vs-svg-performance
  15. 15 http://lea.verou.me/css3patterns/
  16. 16 http://lea.verou.me/css3patterns/
  17. 17 http://bradbirdsall.com/mobile-web-in-high-resolution
  18. 18 http://farukat.es/journal/2010/08/469-pure-css-icons-make-madness-stop
  19. 19 http://css-tricks.com/snippets/css/css-triangle/
  20. 20 http://filamentgroup.com/lab/dingbat_webfonts_accessibility_issues/
  21. 21 http://24ways.org/2011/displaying-icons-with-fonts-and-data-attributes
CSS

↑ Back to topShare on Twitter

David Bushell is a website designer and front-end developer working at Browser Creative, London. He blogs regularly at dbushell.com and xheight, and shares inspiration and web design related interests at Design Heroes. You can also follow him on Twitter.

Advertising

Note: Our rating-system has caused errors, so it's disabled at the moment. It will be back the moment the problem has been resolved. We're very sorry. Happy Holidays!

  1. 1

    Very interesting article..I’ll definitely have to give SVG more of a chance than I have been :)

    Before people blow the comments up with “Blah Blah, not going to use it because it’s not fully supported, blah blah blah”, it’s worthy to note that most of new technologies will always be this way. It’s best to at least start learning and utilizing them in personal projects, so when they are supported, you’re already ahead of the curve and don’t have to spend weeks learning it. Something to think about.

    Also, David, you may be aware, but in your CSS for the Sprite technique, you can condense it a bit more than you did.
    You have:

    background-image: url(‘sprite.png’);
    background-repeat: no-repeat;
    background-color: #ccc;
    font-size: 16px;
    font-weight: bold;
    line-height: 20px;

    which can be replaced with:

    background: #ccc url(‘sprite.png’) no-repeat;
    font: bold 16px/20px;

    And if you do know, maybe someone else didn’t :)

    • 2

      Thanks Alex :) I normally use the shorthand code but in this example I felt it was best to be verbose so that the change between a PNG and SVG file was obvious!

    • 4

      I always use shorthand for ‘background’, but I always forgot using shorthand for ‘font’. Thanks for remembering me.

      Btw, really nice article.

  2. 5

    Inkscape is an excellent open source (ie: free) alternative to Adobe and is fully SVG compliant, I use it for print but never occurred to me to use it for the web. Thanks for the article.

    • 6

      Inkscape is pretty good, but it has some annoying habits. For one, it takes all the attributes like fill, stroke-width, etc, and sticks them in a style attribute. That totally blows away your ability to style your SVG with CSS. Fortunately, there’s an “Optimized SVG” format you can choose in the save as dialog to fix that. You’ll probably still want to optimize a bit more in a text editor though. Values like x=”0.500000000001″ can be quite unsightly.

      SVG is awesome. I’ve got 24 site icons so far that gzip to about 5kb. I had intended to use the SVG element instead of making the file a sprite, but Webkit has a 5 year old bug (#12499) that prevents using the use element with external files. Bummer… :-/

      Firefox and Opera handle it nicely. Opera even supports xpointer. And I don’t even care if IE can render it or not. But there’s webkit… So, it looks like I’ll need to use the more complicated sprite approach and be forced to remember where my icons live in a grid… :-(

      Oh well, that will ‘bloat’ up my icons.svg file to about 6kb gzipped :-) Can’t be helped. Thanks for the article to raise some SVG awareness David.

  3. 7

    Thank you for the great article! It really explains a lot how SVG is indeed a more sensible alternative to some existing techniques. However, I do have a somewhat related question to the matter.

    You mentioned that you created your SVG file in Illustrator, but is there another program for creating SVG files or is in your opinion Illustrator the best one? Frankly, I don’t have the time nor the patience to create SVG files by hand.

    Again, cheers for the superb article!

    V.

    • 8

      Hi Valentin, I don’t do a huge amount of vector work but Adobe Illustrator is my choice. I’d expect most good illustration software can export to SVG – perhaps others can suggest, anyone?

      Beyond basic graphics trying to write the XML by hand would be painful but it’s good to know how things are generated and tweaked.

    • 9

      I’ve used Inkscape, a free and open source alternative to Illustrator. Never having used Illustrator, I can’t speak to how they compare. I can say that it worked well enough to make vector graphics, although the learning curve is very steep.z

      My suspicion, though, is that Inkscape does not really compare to Illustrator as far as quality and usability.

      • 10

        Indeed, Adobe Illustrator is a very good piece of software, but if you want to do something fast and simple (or can’t afford to pay an Illustrator license), then Inkscape is a very good alternative.

      • 11

        When it comes to screen graphics, Illustrator doesn’t have much to offer over Inkscape. Except for a really big price tag.

        Not to start a flame war, but Inkscape has very good quality and its user interface could be argued as even easier to understand than Illustrator’s, depending on how familiar you are with the Adobe user interface.

        Inkscape is also built around the SVG standard. It is actually a WYSIWYG for writing SVG. Inkscape files are SVG files. Illustrator can export to SVG, but when saving to SVG for live website use remember to use the right settings so that the Illustrator binary blob is excluded from the SVG file.

        The real strength of Illustrator at this point in time is obvious in its support of CMYK color mode, mesh gradients (though that’s coming to Inkscape soon) and sophisticated typesetting features as well as being a widely used application, which is important if you plan to collaborate with professional graphic designers.

        There are probably many other important features as well, since Illustrator has been in existence for decades. But I wanted to make it apparent that Inkscape is a very capable tool for creating high quality graphics.

      • 12

        Actually Inkscape is much more usable for this task than Illustrator. It supports all typical vector editing tools, it exports to .svg and what totally surpasses Illustrator – you can create a custom font directly in Inkscape (dingbats on the fly!) AND it has a SVG text editor where you can directly edit the svg nodes.
        Not to mention that Illustrator (I use CS3 since I can’t afford to upgrade each year) crashes a lot on Windows – while in Inkscape I haven’t had a single crash since I’m using it.

        So I would say – for creating svg graphics – specially for preparation of files – Inkscape wins.

        Illustrator users will have problems with the interface for sure since it is a bit different, but for me it’s totally irrelevant – both are equally usable (I used both programs for the same amount of time more or less and didn’t have problems with any of interfaces).

    • 13

      Adobe Fireworks can export to SVG file format, too. You’ll need an extension for this feature to work, though (Export commands pack, by Aaron Beall), but it’s free and easy to install.

      I haven’t much tested it, but I heard very good things about it. HTS! ;)

  4. 14

    Love the article! Finally read an article highlighting all the important details regarding SVGs and sprites.

    I would definitely give making SVGs a try now. :)

  5. 15

    I’d say that until Internet explorer hits > 50% for versions 9 upward, browser compatibility is still going to be a major limiting factor. Even at 50% that will still mean a significant chunk of your userbase won’t be able to see your fancy resolution-independent SVG files.

    That’s not to say it’s not an interesting technology, of course, it certainly is and it’s something the web had needed for a long time. I’m just saying we’re far from the point where we can bin all out PNG/GIF/JPEG files without consequence.

    • 16

      @Gordon: «until Internet explorer hits > 50% for versions 9 upward, browser compatibility is still going to be a major limiting factor.»
      Around 2004 all the time Acrobat was installed, in the browser was placed the SVG plug-in. The percentage of browser with Acrobat plugin (and SVG) was around 96%.
      Still SVG had no whatsoever traction. The w3c specification for SVG was the same of today.
      The cool stuff was CSS and its tricks and hacks.
      Then Adobe bought Macromedia and the Adobe SVG plugin has gone.

      Sebastian

    • 17

      Modernizr is mentioned in the article and in the comments already to solve this issue. There’s no point in waiting, just use fallback solutions.

    • 18

      Gordon I think that would have been a valid point a year ago but since chrome has taken over ie’s title as marketshare leader and then you throw all the other browsers that support SVG the gap just gets bigger.

      http://gs.statcounter.com/

  6. 19

    David, I think you get the SVG perspective wrong.
    You can use the CSS to “style” the SVG file itself.
    The separation between design and content can be total.
    Scenario: you design all the user interface in SVG for an unrest client. When the client want to change the all the colors, all your work is change the value of an attribute.

    Sebastian
    PS
    I invest too much time SVG ten years ago. With my disappointment, it does not pay off.

  7. 20

    Very useful article. I’m definitely planning to give SVG a try. Thank you!

  8. 21

    I think under ‘browser support’ you pretty much identified why they’re ‘one of the most underused technologies in website development today’.

    Without simple workarounds for unsupported browsers, it seems like more trouble than its worth. So yeah great idea, but it’s not nearly ready for us to be worrying about it when making websites. Hopefully in a couple years they’ll be worth paying attention to.

    Good to have svg on radar anyway

    • 22

      He did mention using Modernizr in the article to test for SVG support, i think thats about as simple a workaround as you could ask for, at least when your referencing SVG files in your CSS, obviously its not as simple if your linking SVG in your HTML

  9. 23

    Thanks for this nice article David. Didn’t find any better explanation in one place about SVG.

  10. 24

    Floris Fiedeldij Dop

    January 16, 2012 2:07 pm

    Great article, good example, clearly written and a joy to read. Forwarded this to some developers who could learn from it.

  11. 25

    The zooming on your demo page doesn’t seem to work correctly in Opera :(

  12. 26

    Nice article, I’ve been using raphael.js to play around with SVG lately and am starting to really love it.

  13. 27

    Seriously fantastic article. I’ve been unsure of SVG for a while now but this has cleared a lot up and given me a lot to think about.

  14. 28

    Very knowledgeable article, great example, Thanks a lot for the great article!
    bestkreative.com

  15. 29

    The idéa is not bad… might even come in handy some day. But i think i would rader go with the @font-face :before style and css3 stuff. b/c you get more opportunities with font-face, color, text-shadow, hover and so on. when the site owner turns out the want to change the color scheme it would be easy to just change color. Or if they want diffrent teams.

    I also belive the Voice Speek have to adopt to the the web a bit more. or that the W3C can come up with something both can agree on.
    I hope i someday see a new global attribute to all elements that’s called “icon” (simular to the data-icon”) that is not spoken. that could aswell be started to use now and not about 5 years when all browser have included it.
    You would also need something lik icon-before/after=””

    You must admit, icons is very common. so its now time to approve it in a way its semantic and easy to use.
    prehaps you also could do in your css code:

    voiceSpeeak: none;

  16. 30

    Jimmy Breck-McKye

    January 17, 2012 4:31 am

    Another thing – don’t forget that SVG files, being XML, can be generated by Javascript. If your application allows users to set their own colours or branding (like some kind of white label webapp), that could mean UI elements that adapt accordingly. In the example above, imagine the grey icons taking a coloured hover state that matches the client’s branding. Or an application that uses a large gamut of colours for meaning, which would otherwise need to send absurdly large sprites.

  17. 31

    Superb Article as I ever read about SVG. Thanks a lot.

  18. 32

    If you use Illustrator to design your sites SVGs are a god send.

  19. 33

    You say “mobile browser support is also pretty much across the board,” but this unfortunately isn’t really the case, yet. As your linked chart says, Android doesn’t include in-browser SVG support until Honeycomb, and as that never shipped on phones, only the very newest Ice Cream Sandwich phones (pretty much just the Galaxy Nexus at this point) support SVG. As Froyo (2.2) and Gingerbread (2.3) are by far the most common Android versions in current use, you definitely can’t assume that Android users will see your SVGs.

    • 34

      Thanks for the clarity Andrew, I should have been more specific in regards to “latest versions” for mobile support. As always the right progressive enhancement would make sure non-supporting browsers don’t break (which to be fair is tricky and not without its caveats when SVG is concerned).

    • 35

      It is worse than that; the earlier Android browsers will display any SVG as a white background area, so if you have white text color they simply disappear on Android. I think I will handle this by detecting Android <= 2.3 either on back end or javascript and overriding the elements which have SVG declarations.

  20. 36

    Great article, and a useful technique. I’d like to point out however that this technique is best for high dpi devices, and “bad” for normal or low DPI devices in terms of visual quality.

    There is a very good reason why iconographers re-draw smaller icons rather than simply re-scale a vector. Rescaling usually makes for a blurry and poor result at lower DPI’s.

    So – awesome technique for Retina Things. Less good for everything else (at the moment).

    • 37

      Thanks Matt, very true!

      To be clear I wouldn’t suggest drastically scaling down a very large and detailed icon for the reason you’ve highlighted, and also because the file size would be needlessly large. In my demo I used icons designed for small sizes and they look great even on low PPI screens. The issue of image blur on varying PPI and zoom is resolved, though the “small” vector designs would be of little use at large sizes. So in that case multiple versions would still be required (a logo or app icon, for example). At least until bandwidth is free and browsers can magically render while removing the right details!

      • 38

        No, your Icons are a great example: If you would have cleaned them up right in illustrator, they are a good example of clean, pixel-perfect icons that we are used to see everywhere today. And you scaled them up by exactly 200%. Very easy to render.

        But if you scale the icons/zoom-in by a uneven factor (1,5x oder 2,358x) you get blurry lines or even broken lines. When I zoom into your example in Firefox by one step (guest it’s 125 or 150%) your envelope has 2 different line thicknesses and some lines on the printer disappear at all.

        On high-dpi-displays I don’t see a problem. But on a regular desktop-display it is massive. The (vector-)render-engines in modern browsers are simply not there for quality but only speed. So, with this result, I can’t offer my clients a universal SVG-option, but only on mobile.

  21. 39

    Really interesting post on a topic I’ve wanted to become more mainstream for awhile now.

    Do you ever use SVGs inline in your HTML so that you can add interactivity to them? That seems to be the big sell over Canvas.
    Canvas is quick and good for animations.
    SVGs are good for scaling and interactivity.

    If so what technique would you recommend for doing this – it’s not always ideal to add loads of SVG markup to your HTML markup? Know of any useful resources on this?

    Thanks again for the post.

  22. 40

    “Mobile browser support is also pretty much across the board”
    My problem with SVG both inline or referenced has been its incompatibility with the Android OS and older ios versions (3.2+).

    Canvg gave me a consistent way to efficiently rasterize this SVG content while still taking advantage of the canvas’s performance under additive and subtractive rendering, but that then is incompatible with the css attributes that you and I seem to be used to. Canvg has some great programmatic replacements for these features, but they are typically imported from the SVG itself with embedded effects, dropshadows, or events. I, personally notice no performance difference so far between the browser’s parsing of SVG and Canvg’s.

    Canvg + SVG without css seems to be the most backwards-capable solution for me lately that allows a true device-indepent implementation of my initial design, but will require much more knowledge in svg syntax in styling, animation, etc.

    Hope some of this will help someone avoid the weeks of headaches searching for compatibility that I am finally coming out of.

  23. 41

    I think you can pretty much nullify the size difference issue by creating an svgz image.

    Run this in the terminal: gzip -S z *.svg

    It reduces the file to about ~50% of it’s original size which makes it slightly bigger than the png 1.03kb vs 1.08kb

    Only gotcha is that you need to make sure the svgz is served with the same mime type (image/svg+xml) and that your server has gzip compression switched on.

    • 42

      If you have gzip compression already turned on and set up correctly then there is no need to create a SVGZ file, since gzip will automatically compress the standard SVG file anyway (and as you say, make the file size more comparable to a PNG). SVGZ format is not too well supported in browsers.

  24. 43

    Fonts are probably the best solution for resolution independence and vector icons. If used properly, they can be compatible with screen readers and totally accessible. Icon fonts also have no browser support issue, and they can easily be modified using CSS.

    • 44

      I’d say either option could prove better. One downside of icon fonts is that they are very hard to edit. The tools for creating SVG are vastly superior. But if your interface has a large number of small, single colour icons then it may favour the font technique.

      So it’s not a case of choosing one technique over the other, it’s more dependent on the requirements. I probably could have stated that better in the article! The thinking behind both is what I wanted to highlight though; resolution independence :)

    • 45

      Icon fonts might be easier to support, but SVG has a lot of built in accessiblity that fonts do not have. SVG Icons can be styled with CSS, fonts cannot. SVG icons can be scripted and animated. Again, fonts cannot.

      Fonts are easy to design in inkscape, and easy to support, but they are static and unchanging once created. SVG is the drawing markup of the web. It’s like html for pictures. If anyone is interested in learning more, I would suggest the free ebook available.

  25. 46

    Very useful article. SVG is the future but this is mind blowing too: animated png

  26. 47

    Excellent and very helpful article David ! Thanks for sharing it.

  27. 48

    Thanks for the article. One thought—there is no substitute for pixel-pushed bitmap graphics at very low dimensions, e.g., 16×16 or 8×8. Just as you can’t scale up low-res bitmaps, you can’t scale down vector images.

  28. 49

    Lets say I have an existing site that consists of PNG’s and JPG’s how can I convert those images to a SVG file so mobile can take advantage of this? I’m running only Photoshop CS 4

  29. 50

    here’s a quote from you that shows what’s wrong for me with em:

    “You’ll notice that 1.875 × 10 em multiplied by 16 becomes 30 × 160 — the base size at which we produced the sprite in pixels.”

    1.875 x 10 x 16, 30 x 160 x wtf?

  30. 51

    Hi David,

    Excellent article.

    Thanks & regards
    nair

  31. 52

    Gray Ghost Visuals

    January 18, 2012 10:00 pm

    Perfect timing.
    Thankfully SVG has gained momentum and designers can begin to craft wonderfully crisp, scalable graphics. A huge win for the screen surface and responsive design.

    …………The only problem is deciding what to do about those pesky photographs

  32. 53

    Great article. Well done.

  33. 54

    insightful. thanks for sharing David!

    cheers!

    Luis S.

  34. 55

    if you would just need it for icons, you can also make a font out of them …

  35. 56

    Hakan Save Hansson

    January 27, 2012 5:02 am

    Hi,

    I left a comment a couple of days ago (actually twice). Obviously you didn’t like it. That’s totally okay, but I would appreciate if you could give me some hint why you didn’t like it.

    Please send me an email.

    Thanks!

    — Hakan

    Edit: Hmm.. this comment did show immediately. Maybe not you who erased my previous comment :) I’ll try to find out what is wrong with that one.

  36. 57

    Great article! I’d love to see the web move in this direction.
    One thing that I didn’t see mentioned in your article or in the comments is that if you’re using an icon library for your icons, you’ll want to look at the license. Many of them have a clause that explicitly forbids use in vector or high-res format (since it constitutes redistribution), so before you go using an icon set in SVG, check out the license!

  37. 58

    Great article! Thank you for the article!

  38. 59

    Illustrator (and many other programs that started in print and then added Web) insists on writing @width and @height. But you don’t need them; and as you noticed they get in the way of scaling.

    The @viewBox holds the essential information – the range of coordinates used for the scalable design. So just delete @width and @height; the CSS used to include the scalable image will set the size you actually want to render at.

  39. 60

    I mention a Firefox bug in this article that causes the SVG to be rasterised before it is scaled with CSS background-size resulting in a pixelated graphic.

    The solution (rather than the em hack I suggested here) is to produce the SVG with a much larger viewport. The graphic is still rasterised early, but you can ensure that it is scaled down making the effect less obvious. Other browsers can handle background-size better than Firefox, though there are still many situations where the “scalable” part of SVG is lost in transition (such as with 3D transforms).

  40. 61

    I wrote a SVG image replacement script to deal with the lack of SVG support in some browsers.

    I’ve put it up on GitHub

    The idea is that you have two folders: one with SVG and other other with non-SVG images.

    You embed SVG into your webpage. If the script detects that the browser doesn’t support SVG, it then loops through the non-SVG image directory, finds the replacement and embeds it in the spot where the SVG should be.

    It does work as I’ve used it on a live site.

  41. 62

    Excellent article David. I’m puzzled by one comment. You wrote that you created the SVG sprite in Illustrator and then imported it into Photoshop to create the PNG. How’d ya do that? I’m using CS5, and there’s no option for importing SVG … or maybe I’m overlooking it.

    Thanks!
    Irwin

    • 63

      Hi irwin, I keep a working copy of the vector in Illustrator’s native AI format which import into Photoshop perfectly fine. I only expert to SVG for production, same way you’d export JPG/PNG from a PSD file.

  42. 64

    hi David, this is a great article. Do you know if scaleable vector graphics can be added to a wordpress menu? I would love to use svg in wordpress’s dynamic menu but can’t find anywhere on the net that suggests a way of doing so. Cheers

  43. 65

    Aurel Tirnovanu

    May 2, 2012 3:51 am

    Great article. But what about when you have a big image as background and you want the best quality. For example I’m working on a parallax website and on first slide I have a big image. Now, I’m serving images based on media-queries (yes, multiple size images!).

    A SVG being scalable should server both 320×240 and 2132×1301 users, still the SVG export from Illustrator is 27MB and 20MB gzipped.

    How could I serve this to user, especially knowing some areas of globe have poor internet connection ?

  44. 66

    I just upgraded my skills reading this very helpful article. Really great and very comprehensive. I’ll try to use this techniques in my next designs.

    Thanks for give the best for us, hope you keeping like that.

  45. 67

    Jörn Berkefeld

    July 2, 2012 8:12 am

    Thanks for the great article – I’ve been looking for a solution for SVGs in Opera and FF for quite some time now.
    BTW: I spread your wisdom to stackoverflow ;) http://stackoverflow.com/a/11297217/818732

  46. 68

    The demo is broken. Can you fix? Having trouble getting sprite svg to render natively without a plugin.

  47. 69

    “The problem with these methods is that the browser will download the fallback image before SVG is detected”

    Like Andy already mentioned, you reverse check:

    if (!(Modernizr.svg)) {
    // replace .svg with .png
    }

  48. 70

    Hi! Great article. I made a sprite that looks great in retina-screens. Now, I´ve made a second svg-background because I need this one to repeat-x. It looks pretty odd in my iPhone-retina: Like a forced scale on a bitmap image would. Except when i zoom, the image partly gets sharp. I think the SVG-file is fine, no difference from my working sprite.svg. And i gets sharp when I stop the repeat-x, but uses “no-repeat” instead.

    Is there anything I can do about it?

  49. 71

    SVG can be compressed, cached in many ways. It has too many advantadges, not mentioning you can use it on the HTML (print it the way you love) and you don’t have to worry about requests on server anymore. A good website should have the fewest hits to server and still, every HTML should be way too small. I’m using it like this for many cases since SVG background its a waster method, IMHO.

  50. 72

    SVG is awesome and promising, but integration with Fireworks is important.

    The Export to SVG script doesn’t seem to work, and, for the life of me, I can’t seem to figure it out. Perhaps someone can take a quick look? Thanks!

    Details and images on StackExchange:
    http://graphicdesign.stackexchange.com/questions/11473/export-svg-function-in-fireworks-only-creates-outline

  51. 73

    Great article.
    I have developed my website with this technique, but I had performance issues when I used large svg sprite (e.g. 1000x1000px). If i use the sprite 4 o 5 times in the same page, Safari (iPhone 4, IOS 6) often crashes when i scroll the page or i change the orientation. In addition, the page rendering is very slow. To be sure that the problem was the sprite, i replaced the sprite with a 1000x1000px svg image that only contained a 1000x1000px red square: same behavior. If I use a png image instead a svg one, there are no problems.

    • 74

      Yeah, even the demo is working really slow!!! I think SVG still needs some work for performance.

  52. 75

    Great! I’m using it. Fuck <=IE8.

  53. 76

    Great article that I’ll be sure to reference in the future.

  54. 77

    Hi fellows I´m trying to apply this principle but I´m sure I´m doing somenthing wrong my page is http://www.celsohdzign.com I can´t get to visualiza the svg sprites, or perhaps is not yet supported by the browser.

    Thanks,

  55. 78

    Great article.

    I’d like to know if it should be possible to run the following stuffs too:

    * refer to SVG parts (sub-elements) in the css elements. The idea is to perform a kind of raster sprites… KDE is working actually with SVG render… every element refer to a part of a “global svg file”. Doing it in a web page should permits to draw the antire page and point each element to the corresponding part (bottom-border, backgrounds, etc.).

    * if the above point it’s possible… should I use masks to a generic file (without refer to the sub-element)?

    …I’ve got more ideas but first I need to understand if this is possible and if performances are good…

    Please, if you can post examples ;-)

    TIA

  56. 79

    That sure is a lot of extra code/work just to make that little graphic crisp/clear – at least in this application I’m not sure that benefit outweighs the cost.

  57. 80

    >SVG has consistently proved slower than Canvas as a platform for animating vector graphics;

    Your links didnt back you up on that at all. One did, but its only variable was number of nodes/particles. The MS link didnt even compare SVG to canvas, and the third one showed that SVG is better for higher resolution / less particles, while canvas is better for lower resolution / more particles. Sloppy journalism.

  58. 81

    It seems for a 300px text based logo, I’m getting a file size of 25kb when exporting from Illustrator no matter how I configure the exporter. I’m getting 8kb for a PNG-24.

    Realistically hand-coding xml seems like an impossibility (well, anything with a complex path), so I’m hoping there’s a better solution to exporting complex graphics made in programs like Illustrator or InkScape.

    I know InkScape’s native format is SVG, so maybe file sizes exported from there will be much smaller.

  59. 82

    Nicholas Johnson

    August 20, 2013 4:24 am

    I wrote a little polyfill as a JQuery plugin that detects SVG support, and swaps any SVG images out for a PNG of the same name if necessary. It’s pretty easy to use.

    https://github.com/forwardadvance/svg_alike

    It currently only works on foreground images. I could address this if there was a need.

  60. 83

    Any room for rookies in this blog? I have a 1300w x 722h pixel graphic for my web page which was a .jpg. I took it into Illustrator and saved it as a .svg. Then I loaded it into my CMS Moodle web page. My question is this:

    Is it a reasonably easy venture to make that graphic resize down to mobile phone size automatically? If so, what might the code be and where would I put it exactly. Need detailed instructions for a rookie. If I am out of the ballpark for asking such a thing, please just say something like “hire a svg expert.” I’ll understand.

    Thanks and sorry for what might be a dumb question to the pros…seriously.
    Curious

↑ Back to top