resize font to fit in a div (on one line)

CSS no, Javascript yes

There’s no way you could do this using CSS, but you can do it in javascript/jQuery. To help you with your pseudo code because you already know what to do. It’s just that you don’t know how to detect excess width.

The best way would be to have a DIV with following (at least) style:

position: absolute;
visibility: hidden;
white-space: nowrap;
font-family: /* same as your title's */

then copy your text to it and set some starting font size. Then you can iterate through your while loop and stop when div’s width is appropriate. Then set calculated font size to your original title.

This way this checking will be hidden from user’s eyes and it will therefore work faster as well.

BTW: This is the usual way how auto growing textarea scripts work. They use dummy divs with same style settings as the original text area and adjust area’s height as the user types in text. So Text area can be quite small at first but if user types in lots of text it will auto grow to accommodate content.

While loop optimization

You could optimize your while loop to decrease the number of iterations considerably by doing this:

  1. Set a starting font size.
  2. get test DIV’s width.
  3. calculate width factor between orig_div and test_div.
  4. adjust font size by this factor rather than increase/decrease by one unit
  5. test test_div width

Leave a Comment