JSFiddle - React, Tailwind, and code Playground
by Henry
HTML
<svg id="mysvg" xmlns="http://www.w3.org/2000/svg">
<text id="mytext">my sample text</text>
</svg>
CSS
text {
fill: #000;
fill-rule: evenodd;
font-weight: 700;
font-family: Helvetica-Bold, Helvetica;
font-size: 36px
}
/* just for demo purposes */
html {
padding: 20px;
background: #ccc
}
svg {
width: 100%;
outline: 1px solid red;
background: #fff;
overflow: hidden /* in case you want to play around with the translation */
}
JavaScript
// Find the text element
var mytext = document.getElementById("mytext");
// Get it's bounding box
var bbox = mytext.getBBox();
// Reposition text using the values from its bounding box
mytext.setAttribute("x", -bbox.x);
mytext.setAttribute("y", -bbox.y);
// Top left of text should now be at top-left of SVG (0,0)
// Now update the SVG viewBox so that it is fitted to the text
document.getElementById("mysvg").setAttribute("viewBox", "0 0 "+bbox.width+" "+bbox.height);
// Note that the bbox of the text is not tightly fitted to the text. It includes the em boxes
// of each glyph, so it can have extra space around it. Typically that's above the glyphs
// where accent marks would be (if you used accented characters).