I need a way to predict the width of a string if it were to be added inside an element.
The font size is 16px. My original idea was to do 16px for every character but that ended up being wrong.. Any ideas?
I need a way to predict the width of a string if it were to be added inside an element.
The font size is 16px. My original idea was to do 16px for every character but that ended up being wrong.. Any ideas?
You can append the string to the body like so:
function get_width_of_string() {
var div = document.createElement('div');
div.style.position = "absolute";
div.style.marginLeft = "-99999px";
div.style.display = "inline-block";
div.innerHTML = "this is a string";
document.body.appendChild(div);
var width = div.offsetWidth;
document.body.removeChild(div);
return width;
}
this should return the width of the string