I can't have it "auto-grow" naturally like an inline element would grow horizontally to contain its children.
If there is no decent way, what approach do you believe is feasible? (Like, trying out different widths and checking the height to make sure it didn't go over a certain threshold).
The less "pixel values" I can hardcode in my JS the better, obviously.
Given this HTML
<span>text here</span> you have to read the offsetWidth attribute of the span, which is only assigned when the element itself is added to the DOM without a style that makes it invisible. Technically what this means is that the browser has to be able to visually load the element in the DOM to be able to construct and assign the offsetWidth attribute.
Something like this would work:
var span = document.createElement("span"); span.appendChild(document.createTextNode("text here")); span.style = ""; // to make sure the elment doesn't have "display: none" or such document.body.appendChild(span); // adding it to the DOM var textWidth = span.offsetWidth; // be sure to hide or remove the span if you don't need it anymore
©2020 All rights reserved.