Download "Fit text in box" script


Put this into your <HEAD> section

Put this into your <BODY> section

How to use

You use this script by defining a <DIV> with an ID. This div should contain one <SPAN> tag which holds the text. Example:
<div id="theBox"><span></span></div>
<script type="text/javascript">fitTextInBox('theBox');</script>

The fitTextInBox() function will autofit the text into it's parent DIV. The arguments to this function is the ID of your DIV. The second argument is optional. Use it if you need to define a maximum height. The width of the div is set in the CSS:
    border:1px solid #CCC;
    color: #317082;


Thanks for this post!Works great for shrinking text that is too long, but I can't get it to work for text that is too short... when I try to enter a height limitation, instead of limiting the height of the font, it just hides it behind the next div.Is this what you mean by "the second argument is optional"? I used "height: 25px" in the style to define the height, but it's not working...thanks
Shawn at 08:24PM, 2011/05/19.
let me rephrase...: How do I use the second argument? pls spell it out for me, as I am a total js noob:)
Shawn at 08:27PM, 2011/05/19.
I want this in 480x800 resolution. Please send it to me in native javascript
gags at 08:18PM, 2013/07/09.
This is awesome! Thank you so much it's exactly what I was looking for... I am building a UI that is multi language, so far PERFECT
Rob at 02:18PM, 2014/04/24.
Martin Adámek
Thanks, fittext.js did not work correctly for me, but your solution works perfectly for me - longer texts as well as shorter texts.It just do not react to resize of window (it works just once on loading of page),so I have written this short code to run it automatically after each window resize: (it works for me)<script> function calculate_font_sizes() { fitTextInBox('login-h1'); fitTextInBox('subtittle'); } calculate_font_sizes(); window.addEventListener('resize', calculate_font_sizes);</script>I hope it can help to someone.Martin,
Martin Adámek at 09:07PM, 2014/11/24.

Post your comment

Don't have an avatar? Create one at

Confirmation code:

Go to

About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2019