JavaScript Scale Text to Fit in Fixed Div

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());

Leave a Comment