JavaScript Scale Text to Fit in Fixed Div

I have written a jQuery plugin to do this:

http://michikono.github.com/boxfit

The plugin will scale the text both horizontally and vertically to the maximum available size inside the box and then center it.

The only thing you need to do is define a div with text inside it:

<div id="scale">some text</div>

And then call:

$('#scale').boxfit()

The method will accept some arguments to disable/enable text wrapping and centered alignment.


This is somewhat of a hack, but will do what you want.

<div id="hidden-resizer" style="visibility: hidden"></div>

Place this at the bottom of your page, where it will not be moving other elements on the page.

Then do this:

var size;
var desired_width = 50;
var resizer = $("#hidden-resizer");

resizer.html("This is the text I want to resize.");

while(resizer.width() > desired_width) {
  size = parseInt(resizer.css("font-size"), 10);
  resizer.css("font-size", size - 1);
}

$("#target-location").css("font-size", size).html(resizer.html());

HTML:

<div class="box" style="width:700px">This is a sentence</div>
<div class="box" style="width:600px">This is a sentence</div>
<div class="box" style="width:500px">This is a sentence</div>
<div class="box" style="width:400px">This is a sentence</div>

JavaScript:

$( '.box' ).each(function ( i, box ) {

    var width = $( box ).width(),
        html = '<span style="white-space:nowrap"></span>',
        line = $( box ).wrapInner( html ).children()[ 0 ],
        n = 100;

    $( box ).css( 'font-size', n );

    while ( $( line ).width() > width ) {
        $( box ).css( 'font-size', --n );
    }

    $( box ).text( $( line ).text() );

});

Live demo: http://jsfiddle.net/e8B9j/2/show/

Remove "/show/" from the URL to view the code.