Determine if Text Fits in a Box, and Adjust Font Size Until it Does

Posted Wed Dec 28 @ 12:35:07 PM PDT 2011

On the bingo web application I'm building, one of the problems I had to solve was how to determine if a string of text would fit into a n by n pixel box. If the text didn't fit, then I needed to shrink its font size until it did. So after doing some research, I found a method that works in most browsers (IE 7 and up, Firefox, Chrome and Safari). It doesn't work so well in Opera.

The Setup

You need two "testing" elements on your page. One is used to determine if the text fits into the box vertically (the textarea), the other is used to determine if the longest word can fit horizontally (the span). And of course, you need one element to hold the input (the div).

For the CSS, you define the 'cell' class with a width and height of the square element that you want the text to fit into, and the font type and size:

You also need some simple CSS for the testing elements. The padding acts as padding for the input cell (since it forces the font-size to shrink even more) and the overflow:hidden makes the vertical scrollbar on the textarea disappear so it doesn't interfere with the width calculations.

The JavaScript (requires jQuery)

The function setFontSize, takes a jQuery element and determines the font size that makes the text in that element fit into the box specified by the element's CSS height and width. There are two helper functions, getLongestWord and hasScrollbar. getLongestWord() takes as an argument the cell element and returns the longest whitespace delimited word in the cell. hasScrollerbar() takes a regular DOM element, and determines if it has a scrollbar. In this case, we want to know if the textarea has a scrollbar.

To execute this code do something like this:

You can see a demo here.

<< Home