While having a look through the list of features for developers planned for Firefox 4 earlier today, I noticed this:
You can now use SVG with the
imgelement, as well as the background image in CSS.
I know you can already use SVG in background-image with Safari, Chrome and Opera, and this, coupled with Internet Explorer’s push towards SVG and the strong chance this will be available in IE9, made me decide to take a closer look.
I’ve put together a little demo page which you can view with Safari, Chrome, Opera or Firefox 4 nightlies:
The same image is used many times at different sizes on this page, displaying the grand advantage of SVG over PNG: it can be resized without the same loss of quality that bitmap images suffer.
Implementation is very easy:
E { background-image: url('image.svg'); }
You’ll notice also a box labelled ‘SVGZ’ — the background-image on this element is in the compressed SVG format, SVGZ:
E { background-image: url('image.svgz'); }
The file size is less than one-third of the non-compressed version. In order to use this, you may need to configure your server; full instructions for Apache servers can be found here.
The drawback is that it’s not ready for use just yet — browsers that don’t support SVG in background-image will not provide any fallback, even if you supply another background-image value; so in non-supporting browsers, no image at all will be displayed.
Update: I’ve found a technique for using SVG images with PNG fallback.
The image used in this demo is from All Free Vectors.
Update (21/12/2010): Changed information about SVGZ, thanks to the comment from Robert Longson below.
[…] This post was mentioned on Twitter by Peter Gasston, Kravimir. Kravimir said: RT @stopsatgreen Using SVG in background-image http://bit.ly/9wpeuZ […]
[…] Using SVG in background-image […]
wow that’s great. Never thought using SVG for background is possible!
All browsers support svgz, the trick is that you need Content-Encoding: gzip in the response header for the svgz file.
@Robert Longson: Thanks for that; I’ve tested it and you’re absolutely right, so I’ve updated the post to reflect that.
Great post! I have made a code pen where I show using a SVG based image as background image, pretty cool :-) http://codepen.io/netsi1964/full/npCrH
There’s a small issue — images mentioned in ‘background-image‘ will not be printed by default when user chooses to print your page.