0

How do I resize some text based on the length of the text and the size of the container?

It's for a title. I basically want to say: "If the dynamically generated <h2> has less than 10 characters, increase the font size to 2em to fill the space. Otherwise, leave it at 1em".

Ideally I'd quite like to just resize the text up to a maximum. As in, "the title isn't fully fitting the horizontal space, so increase font size without going onto a second line". Is that doable?

I can't send you a link, since the site isn't live.

bigonroad
  • 7
  • 3
  • 9
  • Check if the following link is helpful. http://stackoverflow.com/questions/1288297/jquery-auto-size-text-input-not-textarea – tamilsweet Dec 23 '11 at 15:35
  • possible duplicate of [Auto-size dynamic text to fill fixed size container](http://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container) – Quentin Dec 23 '11 at 15:42

2 Answers2

0

If you have a fixed-sized container one technique you can use is to detect whether the text is overflowing its container, then reduce the font size until it is no longer overflowing. This way you always get the best fit without counting characters. With proportional fonts, counting characters won't always work.

The technique for detecting overflow is described here:

detect elements overflow using jquery

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • Hey guys. That was helpful - I have a slight confusion - I only want to resize the text under one line. In other words, if its a 15 word title, I am happy for it to span two lines. I only need to resize the text if it is already less than one line. – bigonroad Dec 23 '11 at 16:23
  • You can easily check the height of the element - knowing that it will be one height if it's one line and another if it's two. Then adjust the font accordingly. If you need code help, let me know. jquery's $('.myDiv').height() if what you need. – Diodeus - James MacFarlane Dec 23 '11 at 16:49
  • Appreciate the offer of code help: any idea on my implementation below? Thanks. – bigonroad Dec 23 '11 at 17:23
0

Also checkout Fittext.js. You can look at the source what it does - which is tiny.

airportyh
  • 21,948
  • 13
  • 58
  • 72
  • Hey, so I've tried out fittext.js - you can see here an example page where I want the title to enlarge. What am i doing wrong in the code? http://allaboutchris.org/blog/2011/send-us-out/ – bigonroad Dec 23 '11 at 17:21