Resizing text to fit inside a static div

Go To


Basicly I want a text to resize depending how long the text is. If I wrote "WWWWWWWW" it would be resized to fit inside the 100px div. If i wrote "Test" it wouldn't be resized because it wont break the 100px limit.

I'm sure you get the idea by now. I'm open for anything. Javascript, php, whatever you have to offer.

2012-04-04 18:37
by Mats Bakken
Did you tried word-wrap: break-word or you want resize font size - safarov 2012-04-04 18:40


I think javascript is your friend here, as it allows you to best fit the text regardless of the user's browser window size (if you do it in PHP and oversize/the layout will break for certain users).

I had a similar issue, which made me write my own plugin for this. One solution is to use the shrink-to-fit-approach, as described here. However if you have to fit multiple items or are concerned with performance, e.g., on window resize, have a look at jquery-quickfit.

It meassures and calculates a size invariant meassure for each letter of the text to fit and uses this to calculate the next best font-size which fits the text into the container.

The calculations are cached, which makes it very fast (there is virtually no performance hit from the 2nd resize on forward) when dealing with multiple texts or having to fit a text multiple times, like e.g., on window resize.

Demo for a similar situation as yours

Further documentation, examples and source code are on the project page.

2012-04-09 07:05
by chunks_n_bits


if you use a font that has a fixed width(i.e. all letters are equal width) then you can do this using php or javascript.

count the number of letters in php using strlen. then hard code the font size e.g. this example is showing how it can be done and is not the best way to do. Let me know if you have any questions.

code didnt work properly but

  $fontsize = 11px;


2012-04-04 18:44
by encodes


Do something like this in PHP:

$length = strlen($string);

if($length < 5)
   $added_class = 'short';
elseif($length < 10)
   $added_class = 'medium';
   $added_class = 'long';

echo '<div class="normal_class '.$added_class.'">'.$string.'</div>';

And in your CSS file:

div.short { font-size: 15px }
div.medium { font-size: 13px }
div.long { font-size: 10px }
2012-04-04 18:52
by hohner