1

I'm looking for a way to autoresize the text inside a div to its maximum size. The maximum size is the biggest size possible while still fitting the div.

I know it's not possible to do this in CSS. Is it possible with the use of javascript?

Boyd
  • 723
  • 4
  • 15
  • 32
  • What you mean "auto resize the text? By default, text will wrap to several lines and using CSS you can choose to hide and "excessive" text.. – Shadow The GPT Wizard Oct 24 '11 at 07:46
  • It's an `div` (in this case the `div` of an dashboard widget) containing a number (total visitors of website) with a unknown number of digits. Because that's the only thing the widget shows I want to make the number as big a possible (in size ofcourse). – Boyd Oct 24 '11 at 09:04

1 Answers1

5

You can use such trick in pure JavaScript to "auto resize" the font size:

window.onload = function() {
    var oDiv = document.getElementById("Div1");
    oDiv.style.overflow = "auto"; //for Firefox, but won't ruin for other browsers
    var fontSize = 14;
    var changes = 0;
    var blnSuccess = true;
    while (oDiv.scrollWidth <= oDiv.clientWidth) {
        oDiv.style.fontSize = fontSize + "px";
        fontSize++;
        changes++;
        if (changes > 500) {
            //failsafe..
            blnSuccess = false;
            break;
        }
    }
    if (changes > 0) {
        //upon failure, revert to original font size:
        if (blnSuccess)
            fontSize -= 2;
        else
            fontSize -= changes;
        oDiv.style.fontSize = fontSize + "px";
    }
};

Live test case.

Start with the actual font size of the <div> if you know it, otherwise better use smaller number as the first number.

The above code works on the principle that when the text is bigger than the set width of its container, the scrollWidth property which is the "actual" width will be bigger than the set width.

Edit: Firefox won't update the scrollWidth property if the overflow CSS property is set to its default "visible" value, so you must set it to "auto" - the code is doing it for you, but also possible setting it via CSS if you prefer.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • Are you using firefox? It seems like in firefox the while loop is infinite because it says "Script is not responding". This also happens in your live test case. – Boyd Oct 24 '11 at 10:06
  • Hmm.. tested only in Chrome and IE9. Will take a look now with FF. – Shadow The GPT Wizard Oct 24 '11 at 10:09
  • Thank you that worked! And for those (me too) who want to use this function on the 'onresize' event add the following line before the while loop or else the text size won't decrease when needed. `oDiv.style.fontSize = fontSize + "px";` and add `oDiv.style.overflow = "hidden";` at the bottom of the function to get rid of the scrollbars after resizing – Boyd Oct 24 '11 at 11:20