Background color of text in SVG

Nick Ginanto picture Nick Ginanto · Mar 19, 2013 · Viewed 100.4k times · Source

I want to color the background of svg text similar to background-color in css

I was only able to find documentation on fill, which colors the text itself

Is it even possible?

Answer

sluijs picture sluijs · Jun 1, 2013

No this is not possible, SVG elements do not have background-... presentation attributes.

To simulate this effect you could draw a rectangle behind the text attribute with fill="green" or something similar (filters). Using JavaScript you could do the following:

var ctx = document.getElementById("the-svg"),
textElm = ctx.getElementById("the-text"),
SVGRect = textElm.getBBox();

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("x", SVGRect.x);
    rect.setAttribute("y", SVGRect.y);
    rect.setAttribute("width", SVGRect.width);
    rect.setAttribute("height", SVGRect.height);
    rect.setAttribute("fill", "yellow");
    ctx.insertBefore(rect, textElm);