Is it possible to give SVG <tspan>
element background color? If not, what would be the best way to simulate it?
My goal is to give text background color, and I figured that filling <tspan>
elements would be perfect — they already "outline" text chunks (<tspan>
elements) that represent lines in multiline text.
The example I'm working with:
<text x="100" y="100" font-size="30">
<tspan>hello</tspan>
<tspan x="100" dy="1.2em">world</tspan>
</text>
I tried "fill" attribute but it seems to affect fill (color) of text, not the area behind it:
<tspan fill="yellow">hello</tspan>
I also tried setting background-color via CSS:
<style type="text/css">tspan { background-color: yellow }</tspan>
..but that doesn't work (in at least Chrome 17 and Firefox 12).
Wrapping tspan in <g>
(or text itself in <g>
) with "fill" doesn't work either:
<g fill="yellow"><tspan>hello</tspan></g>
<tspan><g fill="yellow">hello</g></tspan>
Aside from creating a <rect>
element positioned at the same location — something I'd like to avoid — is there another way to achieve this?
A rect is probably the best way to do that (assuming you are only dealing with the simplest forms of text).
The tspans have no "background" themselves in SVG 1.1, the background is whatever gets painted before the tspan. There are many cases to consider, such as the case where a tspan is inside a textPath that has the shape of a circle. Also note that it's not as simple as a continous rectangle in all cases, a single tspan can be skewed, rotated and partitioned into several intersecting and non-intersecting shapes due to transforms, glyph positioning, etc.
There's another way I can think of that would do this without scripting, but then you'd need to know the width of the string in advance (e.g by using a monospaced font). If you have that then you can add another tspan element using the Ahem font, placing it before the other tspan in the document and giving it the same x,y position as the tspan you want to give a "background".
Otherwise the way to do this is through scripting, and adding rectangles (or tspans with an Ahem-like font).
SVG does not support directly specifying an image background color...but you can adjust the four values of the viewBox attribute (complicated). I know it's something you want to avoid, but CSS wouldn't help you.
...or you can use getBBox and getCTM...it would give you advantages for rotated text. EXAMPLE: http://srufaculty.sru.edu/david.dailey/svg/getCTM.svg