Font size auto adjust to fit

后端 未结 7 1807
夕颜
夕颜 2020-12-09 09:06

I\'m trying to do what the title says. I\'ve seen that font-size can be a percentage. So my guess was that font-size: 100%; would do it, but no.

7条回答
  •  感情败类
    2020-12-09 10:08

    Here is another jQuery solution ...

    /**
     * Resizes page header font-size for the text to fit.
     * basically we add a hidden span into the header,
     * put the text into it and then keep reducing the super large font-size
     * for as long as the height of the span exceeds the super
     * tall line-height set for the test (indicating there is more than one line needed
     * to show the text).
     */
    function setPageHeaderFontSize(selectorString) {
        jQuery(selectorString).each(
            function(i, el) {
                var text = jQuery(el).text();
                var length = text.length;
                if(length) {
                    var id = "TestToSeeLengthOfElement_" + i;
                    jQuery(el).append("");
                    var innerEl = jQuery("#"+id);
                    var height = 301;
                    var fontSize = 200;
                    while(height > 300 && fontSize > 10) {
                        height = jQuery(innerEl).css("font-size", fontSize).height();
                        fontSize--;
                    }
                    jQuery(innerEl).remove();
                    jQuery(el).css("font-size", fontSize+"px");
                }
            }
        );
    }
    
    //you can run it like this... using any jQuery enabled selector string (e.g. h1.pageHeaders works fine). 
    setPageHeaderFontSize("#MyDiv");
    

提交回复
热议问题