view raw
Javiere Javiere - 6 months ago 25
CSS Question

Style within background-image css of SVG not working in IE

I am setting icons by applying classes to elements, so this classes changes the property background-image and sets an url to it.

Let's see an example:

.example-icon {background-image: url("data:image/svg+xml,");}

Which just contains this svg but url encoded:

<svg id='Layer_1' xmlns='' viewBox='0 0 195.6 107.8'><path fill='#B5B5B5' class='st0' d='M97.8 107.8c-2.6 0-5.1-1-7.1-2.9L2.9 17.1C-1 13.2-1 6.8 2.9 2.9 6.8-1 13.2-1 17.1 2.9l80.7 80.7 80.7-80.7c3.9-3.9 10.2-3.9 14.1 0 3.9 3.9 3.9 10.2 0 14.1l-87.8 87.8c-1.9 2-4.4 3-7 3z'/></svg>

This works perfectly (encoded in all browsers and decoded only in Chrome) but the problem comes when I try to set any style within the SVG. For example:

<svg version="1.1" id="Layer_1" xmlns="" xmlns:xlink="" x="0px" y="0px"
viewBox="0 0 20 20" width="20" height="20" style="enable-background:new 0 0 20 20;" xml:space="preserve">
<style type="text/css">
<circle class="st0" cx="10" cy="10" r="9.5"/>
<path class="st1" d="M5,10h10 M10,5v10"/>

That is just another SVG but with styling inside, the problem is that this will not work (coded or decoded) in IE 11.

Here the encoded version I am using:

I am aware that IE only loads properly formed url's but that is an encoded one.

Any ideas about what can be happening?

Edit: it is required that data is not encoded in base 64.


The <style> {...} </style> element caused you problems with parsing the CSS content. You can overcome this by using a base64 encoded string instead of a URL encoded string:

.example-icon {
  background-image: url('data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJMYXllcl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDIwIDIwIiB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDIwIDIwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+IDxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI+IC5zdDB7ZmlsbDojMDBGRkZGO3N0cm9rZTojRkY3Njc2O3N0cm9rZS1taXRlcmxpbWl0OjEwO30gPC9zdHlsZT4gPGNpcmNsZSBjbGFzcz0ic3QwIiBjeD0iMTAiIGN5PSIxMCIgcj0iOS41Ii8+IDxwYXRoIGNsYXNzPSJzdDEiIGQ9Ik01LDEwaDEwIE0xMCw1djEwIi8+IDwvc3ZnPg==');
  width: 20px;
  height: 20px;
<div class="example-icon"></div>

Checked in chrome, firefox, safari, ie>=9

update - no base64 requirement

The encoded url will work if you remove all line-breaks (\r\n) and tabs (\t) from the string before encoding:

.example-icon {
  background-image: url("data:image/svg+xml;charset=utf-8,");
  width: 20px;
  height: 20px;
<div class="example-icon"></div>

Also checked in chrome, firefox, safari, ie>=9