Fit text to element with inflateText.js

InflateText.js began as these things often do: with a problem. One of my projects required headlines that would fit the horizontal space available like a headline screaming from the top of a newspaper. A quick survey of the internet turned up FitText.js, a great tool for adjusting text to fit into giant spaces. FitText scales font sizes based on the width of the parent element—efficient, but it runs into trouble when used on content with variable character widths.

The obvious answer was to adapt the scaling factor based on the width of the text, rather than just its font size. The result is the capital-H Hack at the heart of inflateText:

var mask = $('<div style="height:1px;overflow:hidden;"></div>')
    test = $this.clone().css({
    width = test.width();


Three things are happening here. First, a “test” element containing the same text as the headline is appended to the body inside a 1px tall mask. Its width is calculated, and the mask is removed. Assuming that the point size of the font (96px) and the width of the original containing element are known, the point-size required to fill the original container can be calculated as a simple ratio:

`var fontSize = 96 * parent.width() / width`

Hack, yes, but it works.

### Using inflateText

Fortunately, inflateText ([Github](, [Demo](<a href=)) wraps that all up in to a tidy jQuery plugin. In the simplest case, it looks like this:


A few additional options can be used to adjust the scaling factor, minimum, and maximum font size. To constrain text to 80% of the available area and the font sizes to between 32 and 96px, just use:

$(‘h1’).inflateText({ maxFontSize: 96, //(px) minFontSize: 32, //(px) scale: 0.8 });```

In closing

As with all javascript shims, inflateText provides enhancement rather than 100% reliability. Be sure to set a default style for visitors without javascript before applying the plugin. If you’re planning to use it on mobile devices, it’s also a good idea to set the minFontSize parameter to ensure that the text remains legible on narrow screens.

Related Links