Skip to content

Instantly share code, notes, and snippets.

@DigiTec
Last active December 14, 2015 04:19
Show Gist options
  • Save DigiTec/5027055 to your computer and use it in GitHub Desktop.
Save DigiTec/5027055 to your computer and use it in GitHub Desktop.
This Gist uses a cached, hidden div in order to measure height/width of text. Imperfect since I'm still technically inheriting styles through the body that could affect my offsetWidth and offsetHeight but most likely a better approximation than measuring the width of the "M" character which is often a suggestion when dealing with the lack of hei…
(function () {
var _cachedDiv;
function domMeasureText(text, font) {
if (!_cachedDiv) {
_cachedDiv = document.createElement("div");
_cachedDiv.style.visibility = "hidden";
_cachedDiv.style.position = "absolute";
document.body.appendChild(_cachedDiv);
}
_cachedDiv.style.font = font;
_cachedDiv.innerText = text;
return { width: _cachedDiv.offsetWidth, height: _cachedDiv.offsetHeight };
}
this.domMeasureText = domMeasureText;
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment