What dependency between font-size and width of char in monospace font? In my web-application I use \"courier new\" font. I want to know, what realy length in pixels of string? I
Each monospace font would have its own ratio between pixel length and font-size. But since we would ideally express font family's as several options to give the browser a wide range to fulfill the style (in case it doesn't have the font required), this method may be flawed even if you do find the ratio. Also who is to say that "Courier New" has the same spacing/sizing/... on one device as on another?
One sure way to tell this is to use JavaScript, clone the element and check the size values on the fly.
take a look at this fiddle for an example of this
http://jsfiddle.net/zUFwx/ (code references jQuery)
function getSizeOfTextInElement(domElement) {
var $element = $(domElement),
$clone = $element.clone(),
size = {
width : 0,
height : 0
};
$clone.addClass("sizingClone");
$(document.documentElement).append($clone);
size.width = $clone.width();
size.height = $clone.height();
$clone.remove();
return size;
}
var elementToCheck = document.getElementById("checkSizeExample"),
sizeOfElement = getSizeOfTextInElement(elementToCheck),
message = "element has a width of " + sizeOfElement.width + "px";
$("#result").text(message);