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

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

I have a div with some text:

With some text in it

How can

相关标签:
5条回答
  • 2021-01-04 13:56

    Contrary-wise. You could wrap the text in an interior DIV, measure its width with JavaScript. Test if that width is wider than the parent DIV. Get the current font size, and incrementally move it down 1px at a time until inner DIV's width is less than or equal to the outer DIV's width.

    0 讨论(0)
  • 2021-01-04 13:57

    Came across this JQuery plugin in my quest to find the same.

    Github

    Demo

    0 讨论(0)
  • 2021-01-04 13:58

    Also came across this Jquery script when I was looking for the same thing. It has the added benefit over the others, as far as I quickly tell, is that it also adjusts for height as well as width.

    Comes from here: http://www.metaltoad.com/blog/resizing-text-fit-container

     function adjustHeights(elem) {
          var fontstep = 2;
          if ($(elem).height()>$(elem).parent().height() || $(elem).width()>$(elem).parent().width()) {
            $(elem).css('font-size',(($(elem).css('font-size').substr(0,2)-fontstep)) + 'px').css('line-height',(($(elem).css('font-size').substr(0,2))) + 'px');
            adjustHeights(elem);
          }
        }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-01-04 14:08

    Short Answer: You don't.

    You would have to try a size, render it, see if it fits, try another size, render it see if it fits, etc. Then you have to handle the case where the calculated font size is so small no one can read the text.

    There are other options, if the text doesn't fit, add an ellipsis (...) to the end of the text, when you mouse over it, the div could expand, you could use a popup window or tooltip with the full text, or put the full text in a larger area of the screen.

    Find another way.

    0 讨论(0)
提交回复
热议问题