How can I autoscale the font size to fit the contents of a div?

后端 未结 5 1551
广开言路
广开言路 2021-01-04 13:42

I have a div with some text:

With some text in it

How can

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 14:06

    I've been doing something like this, to set the text scale relative to the parent (or window) width / height. You can avoid jQuery by using offsetWidth and offsetHeight instead of width.

    var setBodyScale = function () {
    
        var scaleSource = $(window).width(), // could be any div
            scaleFactor = 0.055,
            maxScale = 500,
            minScale = 75; //Tweak these values to taste
    
        var fontSize = (scaleSource * scaleFactor) - 8; //Multiply the width of the body by the scaling factor:
    
        if (fontSize > maxScale) fontSize = maxScale;
        if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums
    
        $('html').css('font-size', fontSize + '%'); // or em
    }
    

提交回复
热议问题