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 {
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 its bounding box
var bbox = mytext.getBBox();
// Now update the SVG viewBox so that it is fitted to the text
document.getElementById("mysvg").setAttribute("viewBox", [bbox.x, bbox.y, bbox.width, bbox.height].join(' '));
// 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).