Benmay Benmay - 19 days ago 6
CSS Question

How to change SVG color (when using the SVG as background in CSS)

I'm struggling to change the color of an svg object via css (svg as background css).

I have this

span {
display:block;
width: 12px;
background: url('data:image/svg+xml;utf-8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><polygon points="6,4.5 0,0 0,1.208 6,5.708 12,1.208 12,0"/></svg>');
height: 20px;
}


This works, but the color of the element is always black. I would like to change it color to a custom color (blue for example).
By adding
style="fill:#2C30FF"
, the element just disappears and shows nothing, although this work fine if the svg element is included in the html (not css background)

See the fiddle for an example. There should display 3 elements but the second doesn't show because I added
style="fill:#2C30FF"


JsFiddle

Why doesn't it work? Would really appreciate some tips.

Answer

# is a reserved character in URLs, it indicates the start of a fragment identifier.

You need to URL encode the # as %23

background: url('data:image/svg+xml;utf-8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><polygon points="6,4.5 0,0 0,1.208 6,5.708 12,1.208 12,0" style="fill:%232C30FF;"/></svg>');

Updated fiddle

Comments