Font scaling based on width of container

后端 未结 30 3043
面向向阳花
面向向阳花 2020-11-21 04:35

I\'m having a hard time getting my head around font scaling.

I currently have a website with a body font-size of 100%. 100% of what though? This seems t

30条回答
  •  梦如初夏
    2020-11-21 05:17

    My own solution, jQuery-based, works by gradually increasing the font size until the container gets a big increase in height (meaning it got a line break).

    It's pretty simple, but works fairly well, and it is very easy to use. You don't have to know anything about the font being used, everything is taken care of by the browser.

    You can play with it on http://jsfiddle.net/tubededentifrice/u5y15d0L/2/

    The magic happens here:

    var setMaxTextSize=function(jElement) {
        // Get and set the font size into data for reuse upon resize
        var fontSize=parseInt(jElement.data(quickFitFontSizeData)) || parseInt(jElement.css("font-size"));
        jElement.data(quickFitFontSizeData, fontSize);
    
        // Gradually increase font size until the element gets a big increase in height (i.e. line break)
        var i = 0;
        var previousHeight;
        do
        {
            previousHeight=jElement.height();
            jElement.css("font-size", "" + (++fontSize) + "px");
        }
        while(i++ < 300 && jElement.height()-previousHeight < fontSize/2)
    
        // Finally, go back before the increase in height and set the element as resized by adding quickFitSetClass
        fontSize -= 1;
        jElement.addClass(quickFitSetClass).css("font-size", "" + fontSize + "px");
    
        return fontSize;
    };
    

提交回复
热议问题