Using SVG in background-image

Warning This article was written over six months ago, and may contain outdated information.

While hav­ing a look through the list of fea­tures for devel­op­ers planned for Fire­fox 4 ear­li­er today, I noticed this:

You can now use SVG with the img ele­ment, as well as the back­ground image in CSS.

I know you can already use SVG in background-image with Safari, Chrome and Opera, and this, cou­pled with Inter­net Explor­er’s push towards SVG and the strong chance this will be avail­able in IE9, made me decide to take a clos­er look.

I’ve put togeth­er a lit­tle demo page which you can view with Safari, Chrome, Opera or Fire­fox 4 nightlies:

SVG in back­ground-image demo

The same image is used many times at dif­fer­ent sizes on this page, dis­play­ing the grand advan­tage of SVG over PNG: it can be resized with­out the same loss of qual­i­ty that bitmap images suffer.

Imple­men­ta­tion is very easy:

E { background-image: url('image.svg'); }

You’ll notice also a box labelled ‘SVGZ’ — the background-image on this ele­ment is in the com­pressed SVG for­mat, SVGZ:

E { background-image: url('image.svgz'); }

The file size is less than one-third of the non-com­pressed ver­sion. In order to use this, you may need to con­fig­ure your serv­er; full instruc­tions for Apache servers can be found here.

The draw­back is that it’s not ready for use just yet — browsers that don’t sup­port SVG in background-image will not pro­vide any fall­back, even if you sup­ply anoth­er background-image val­ue; so in non-sup­port­ing browsers, no image at all will be displayed.

Update: I’ve found a tech­nique for using SVG images with PNG fall­back.

The image used in this demo is from All Free Vec­tors.

Update (21/12/2010): Changed infor­ma­tion about SVGZ, thanks to the com­ment from Robert Long­son below.

7 comments on
“Using SVG in background-image”

  1. […] This post was men­tioned on Twit­ter by Peter Gasston, Krav­imir. Krav­imir said: RT @stopsatgreen Using SVG in back­ground-image […]

  2. […] Using SVG in background-image […]

  3. wow that’s great. Nev­er thought using SVG for back­ground is possible!

  4. All browsers sup­port svgz, the trick is that you need Con­tent-Encod­ing: gzip in the response head­er for the svgz file.

    Robert Longson [December 21st, 2010, 09:02]

  5. @Robert Long­son: Thanks for that; I’ve test­ed it and you’re absolute­ly right, so I’ve updat­ed the post to reflect that.

  6. Great post! I have made a code pen where I show using a SVG based image as back­ground image, pret­ty cool :-)

  7. There’s a small issue — images men­tioned in ‘back­ground-image‘ will not be print­ed by default when user choos­es to print your page.