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:
- Set a starting font size.
- get test DIV's width.
- calculate width factor between orig_div and test_div.
- adjust font size by this factor rather than increase/decrease by one unit
- test test_div width
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…