What dependency between font-size and width of char in monospace font?

前端 未结 3 795
天涯浪人
天涯浪人 2021-02-07 15:15

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

3条回答
  •  一整个雨季
    2021-02-07 15:50

    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);
    

提交回复
热议问题