Using an Data URI SVG as a CSS background image

jon picture jon · Dec 6, 2012 · Viewed 17.6k times · Source

Backstory:

  • Goal: create a triangular shadow that can be applied via CSS and is scale-independant (i.e. a vector, not a raster image)
  • After much research (tho I'm certainly open to alternatives) I chose to use an SVG background image as a data uri (to avoid the extra HTTP request).
  • I know that this can work: http://jsfiddle.net/6WAtQ/

Where I'm stuck:

  • I created a simple svg triangle, with a Gaussian blur effect, if it's written directly in the HTML (as opposed to the CSS) the svg works perfectly: http://jsfiddle.net/RAKWB/

    <svg class="shadow" xmlns="http://www.w3.org/2000/svg" version="1.1"> <defs> <filter id="f1"> <feGaussianBlur in="SourceGraphic" stdDeviation="5" /> </filter> </defs> <polygon points="200,0 200,200 0,200" filter="url(#f1)"/> </svg>​

  • So I tried to replicate the above ( http://jsfiddle.net/6WAtQ/ ) using my own triangle svg,

  • I replaced the hash signs with '%23', but no dice
  • It's not working: http://jsfiddle.net/ZPWxK/1/

    body { background-image: url("data:image/svg+xml;utf8,data:image/svg+xml;utf8,<svg class="shadow" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs><filter id="f1"><feGaussianBlur in="SourceGraphic" stdDeviation="5" /></filter></defs><polygon points="200,0 200,200 0,200" filter="url(%23f1)"/></svg>"); }

Thoughts?

Answer

Robert Longson picture Robert Longson · Dec 6, 2012

See how the working fiddle has double quotes just inside the url() and then all the SVG content uses single quotes? You need to do the same. Otherwise the parser doesn't know where the url content ends.

Alternatively you could make the url use single quotes and keep your SVG content the same.

body { background-image: url('data:image/svg+xml;utf8,<svg class="shadow" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs><filter id="f1"><feGaussianBlur in="SourceGraphic" stdDeviation="5" /></filter></defs><polygon points="200,0 200,200 0,200" filter="url(%23f1)"/></svg>'); }