JavaScript: Resizing text to fit in a container

This span is too big for this div

Filed under:

This span is too big for this div

This is a simple problem and a simple solution. Often in the world of dynamic data we find ourselves with data that is larger than the container. There are ways of handling this like a scrolling div or adding ellipses to chopped of text, but what if you absolutely must see all of the text and are willing to change to font size to accomplish this? Using this little recursive jQuery snippet you can accomplish this.

function adjustHeights(elem) {
var fontstep = 2;
if ($(elem).height()>$(elem).parent().height() || $(elem).width()>$(elem).parent().width()) {
$(elem).css('font-size',(($(elem).css('font-size').substr(0,2)-fontstep)) + 'px').css('line-height',(($(elem).css('font-size').substr(0,2))) + 'px');

Here's the same div as above with the script applied:

This span is too big for this div

You can modify the fontstep variable to resize at a faster rate if you want. I find that resizing in increments of two makes the most sense. That's all there is to it. Enjoy.

EDIT: I added a bit of a timeout to give the webfont time to load first...

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.