_8jxgw
Last Updated: December 13, 2017
·
37.4K
· iam4x

Autoresize text to fit into a div (width & height)

Hi coders!

After trying severals JavaScript snippets and libs for fitting text into a div I was unhappy because none of these were taking care of the 'height' of the DIV and the text could overflow...

So I wrote this simple function in CoffeeScript which tests if the text overflow the div and it will decrement his size until it fits!

The function looks for elements tagged with the .resize class and just resize them.

Simple isn't it?

autoSizeText = ->
    elements = $('.resize')
    console.log elements
    return if elements.length < 0

    for el in elements
      do (el) ->

        resizeText = ->
          elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px'
          $(el).css('font-size', elNewFontSize)

        resizeText() while el.scrollHeight > el.offsetHeight

And here is the JavaScript compiled version :

var autoSizeText;
autoSizeText = function() {
  var el, elements, _i, _len, _results;
  elements = $('.resize');
  console.log(elements);
  if (elements.length < 0) {
    return;
  }
  _results = [];
  for (_i = 0, _len = elements.length; _i < _len; _i++) {
    el = elements[_i];
    _results.push((function(el) {
      var resizeText, _results1;
      resizeText = function() {
        var elNewFontSize;
        elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
        return $(el).css('font-size', elNewFontSize);
      };
      _results1 = [];
      while (el.scrollHeight > el.offsetHeight) {
        _results1.push(resizeText());
      }
      return _results1;
    })(el));
  }
  return _results;
};

You can find an example on JSFiddle : http://jsfiddle.net/mn4rr/1/
You can also contribute on Github : https://gist.github.com/iam4x/5015270

Have fun!

Say Thanks
Respond

8 Responses
Add your response

11972
Ybluwnaz normal

Hey, I'm new to JS and I've never heard of Coffeescript to be honest. I am having the same problem you were having and this solution seems perfect to me. I have tried to put your Javascript version in to script tags at the bottom of my page and it still doesn't work. If it is JavaScript compiled does that mean I have to add something extra somewhere in my HTML page? Or maybe you could tell me how to add the coffeescript version to my page? As I am not so sure how to do that either.
Thanks a million,

over 1 year ago ·
11973
Ybluwnaz normal

Also, could this possibly work if the text that was inside of the div, was set a responsive size (ie: textcontainer { width: 50%; height: 50%; position: absolute; top: 5%; left 5%; background-color: grey; })? And if so, would there be a way for this to auto-resize the text as the user was re-sizing their browser window?

Thanks for your time!

over 1 year ago ·
11997
Ybluwnaz normal

Nevermind, got it to work.

over 1 year ago ·
16014
7bd274d2c4617ebac4df0ee0139af525

With a little bit of modification, you can make this into a nifty little jQuery plugin:

Edit: I've made this a gist because it's going to look cleaner: https://gist.github.com/iamkirkbater/ee9741a02431290682e6

over 1 year ago ·
17722
Default profile 3 normal

Hiya,

I took the freedom to put the example on JSFiddle back to working order.. someone ruined it previously.
On the framework and extensions select jQuery 2.1.0 (w/all the options set) and onload.
This will have it working.
I also took the freedom to size the divs so that the readability of the result is a bit improved.
You may find it at http://jsfiddle.net/mn4rr/709/

And to the author of this code: Thank you, you saved my day! I owe you one, bro.

--inverse

over 1 year ago ·
29237

There is a crazy issue: The autoSizeText does not work on iOS (in my case iPhone 6s) if you use a @font-face font instead of "sans-serif" or some standard font. It is still doing some resizing but at the end the text is way to small. This must be related to some Safari on iOS text-sizing behaviour. Has anyone an idea to solve this?

4 months ago ·
29239

I found a bit of a solution: if you put in jQuery window on load instead of document ready it works but you have a visibile resizing. Why does it work in document ready on a desktop (firefox) and not in iOS if you use a custom font via font-face? That is very interesting...

4 months ago ·
29295

Thanks for sharing this. I liked it so much, I made a jQuery version:

(function() {
  var elements = $('.resize');
  if(elements.length < 0) {
    return;
  }
  elements.each(function(i, element) {
    while(element.scrollWidth > element.offsetWidth || element.scrollHeight > element.offsetHeight) {
      var newFontSize = (parseFloat($(element).css('font-size').slice(0, -2)) * 0.95) + 'px';
      $(element).css('font-size', newFontSize);
    }
  });
})();

Two embellishments: adjusts for both width and height, and scales back by 95% each time rather than 1 for a tighter fit.
JSFiddle: http://jsfiddle.net/p03ht738/1/

3 months ago ·