Alex Rivera | Logout

JavaScript Scale Text to Fit in Fixed Div

Asked 2010-11-12T14:54:14.990
59

In JavaScript/jQuery, how can I scale a varying-length line of text inside a fixed-width Div so that the one line always fits inside the Div (as one line)?

Edit
Report

1 Answer

5

I don't know of an exact way, but here's an approximation:

var factor = 1/3;  // approximate width-to-height ratio
var div = $('#mydiv');
div.css('font-size', div.width() / (div.text().length * factor) + 'px');

You will need to adjust factor based on the font you are using. 1/3 seems to work okay for Times New Roman.

answered 2010-11-12T15:16:52.600

Your Answer