dynamically changing the size of font size based on text length using css and html

前端 未结 8 1264

I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.<

8条回答
  •  旧时难觅i
    2020-12-08 04:58

    Thanks putvande for letting me know the general method. Here is an improved version.

    1. Get rid of the callback hell.
    2. Fixed some bugs may cause page hang.

    Same HTML:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis dui felis, vel vehicula tortor cursus nec

    Here is the function:

    resize_to_fit($('#outer'), $('#outer div'));
    
    function resize_to_fit(outer, inner) {
        while(inner.height() > outer.height()) {
            var fontsize = parseInt(inner.css('font-size')) - 1;
            inner.css('font-size', fontsize);
            // some browsers(chrome) the min font return value is 12px
            if(fontsize <= 1 || parseInt(inner.css('font-size')) >= fontsize+1)
                break;
        }
    }
    

提交回复
热议问题