Posts Tagged ‘printer friendly’

Resize text automatically to fit into a fixed size container using JQuery

September 12th, 2012 No comments

Sometime we want to fix the height and the width of a container and fill text in it as much as it can. For example, we have a customer invoice address box, and we want the address to be shown as large as possible while fitting all in the address box.

In normal case, when the text getting longer and being excessive, it expands the container in HTML. We can put CSS overflow property so it wouldn’t expand the container, but in return, we lose the excess text. So can we resize and scale the text automatically to fit into the container without losing and text? One approach checking the text length in PHP and resize their font-size to maximum possible, but the text size can be different across browsers and this does not work on dynamic text (where the user can input and change the text). Therefore, the easier and more accurate way is using JQuery.

There is a light JQuery plugin TextFill can do the job easily. (demo)


<div id="myTextFillContainer" style="width: 200px; height: 200px;">
  <span>blah blah blah text to be auto-sized</span>


$(document).ready(function() {
    $('#myTextFillContainer').textfill({ maxFontPixels: 36 });

Simply select myTextFillContainer div and use the textfill() function, input a max font size to be 36px, that’s it!


Long Text

Long Text

Short Text

Short Text


We can have multiple containers with different text tag other than span:

$('#myTextFillContainer1').textfill({ minFontPixels: 10, maxFontPixels: 20, innerTag: 'div' });
$('#myTextFillContainer2').textfill({ minFontPixels: 5, maxFontPixels: 10, innerTag: 'span' });
<div class="myTextFillContainer1" style="height: 180px;">
  <div>blah blah blah text to be auto-sized</div>
<div class="myTextFillContainer2" style="height: 120px;">
  <span>blah blah blah another text to be auto-sized</span>

There are few common options:
minFontPixels: the minimum font size
maxFontPixel: the maximum font size
innerTag: the text wrapper tag
complete: callback when all is done