I'm trying to get a SVG 'text' element fitting inside of a svg 'rect' element. e.g. In the example below, I used a monospace text of 5 chars with a font-size of 100px and I expected to have a bounding rectangle close to the text.
But there is a blank gap at the right of the text.
<svg xmlns="http://www.w3.org/2000/svg" height="200" width="1000">
<text x="10px" y="110px" style="font-family:monospace;font-size:100px;">HELLO</text>
<rect x="10px" y="10px" width="500px" height="100px" style="stroke:blue;fill:none;"/>
</svg>
What CSS selectors should I use for the 'text' element ?
Note: I don't want to use the text-on-a-path method. Just a font with a fixed size.
Thanks;
Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .
You can not change the font size or font width because SVG is not a font. It is Scalable Vector Graphics. If you would have some text in your SVG then you could do something with the font from the text element. To see the effect you have to move your mouse cursor over this SVG (in snippet, wich must be runned).
The SVG <text> element draws a graphics element consisting of text. It's possible to apply a gradient, pattern, clipping path, mask, or filter to <text> , like any other SVG graphics element. If text is included in SVG not inside of a <text> element, it is not rendered.
The size of a font determines its height, not its width; and characters are rarely square.
So as far as I know, there's no way to determine the width of even monospace text reliably through CSS.
Well, CSS3 has the ch
unit, which is the width of the 0
character. That would work for monospace text. But it's not supported in SVG.
You could just set a fixed width in pixels, of course. A width of 300 pixels works for me. But then if someone else uses a different monospaced font that fixed width could be off. If you add the font-family:monospace;font-size:100px;
on the <rect>
too, you can set the width of the rectangle in em
s. But I don't think that's any more reliable.
You can, however, use scripting. You can use getComputedTextLength()
to get the text length of a text element:
<script type="text/javascript">
document.getElementById('rect').setAttribute(
'width',
document.getElementById('text').getComputedTextLength()
);
</script>
Adding that at the end of your SVG (and adding the appropriate element IDs) works in Opera 10, Firefox 3.5 and Safari 4.0, at least.
And while you're at it, you could use getBBox()
too, to get the text element's bounding box so you can set the height of the rectangle to match the font size too, in case you ever decide to change the font size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With