Set Font Size Based On Word Count

Chris Coyier //

In my little Quotes on Design project, some of the quotes are longer than others. I thought it might be kind of nifty to beef up the font-size on the shorter quotes and trim down the size for the longer quotes so they all match a bit better in terms of the size they take up on the screen.

Rather than do this with a hard-coded number in each of the quotes, I did it with JavaScript. This allows for easier adjustments down the road and nicely keeps content and presentation separate.

The Plan

  • Set an object of the paragraph you are targetting
  • Split the paragraph into an array of words, breaking at every space
  • Count the length of the array
  • Set the font-size based on that count.

Doing it with MooTools

window.addEvent('domready',function() {
	
	$quote = $$('.post p')[0];
    
        var $numWords = $quote.get('text').split(' ').length; 
    
        if (($numWords >= 1) && ($numWords < 10)) {
                $quote.setStyle('font-size','36px');
        }
        else if (($numWords >= 10) && ($numWords < 20)) {
                $quote.setStyle('font-size','32px');
        }
        else if (($numWords >= 20) && ($numWords < 30)) {
                $quote.setStyle('font-size','28px');
        }
        else if (($numWords >= 30) && ($numWords < 40)) {
                $quote.setStyle('font-size','24px');
            }
        else {
                $quote.setStyle('font-size','20px');
        };
});

Doing it with jQuery

$(function(){

    var $quote = $(".post p:first");
    
    var $numWords = $quote.text().split(" ").length;
    
    if (($numWords >= 1) && ($numWords < 10)) {
        $quote.css("font-size", "36px");
    }
    else if (($numWords >= 10) && ($numWords < 20)) {
        $quote.css("font-size", "32px");
    }
    else if (($numWords >= 20) && ($numWords < 30)) {
        $quote.css("font-size", "28px");
    }
    else if (($numWords >= 30) && ($numWords < 40)) {
        $quote.css("font-size", "24px");
    }
    else {
        $quote.css("font-size", "20px");
    }    
	
});

Examples

Quotes on Design is using the jQuery version. MooTools example here (note some slight changes in the code to accommodate two quotes on one page). This is the first time I've every played with MooTools really. I'm excited to learn more. I am obviously pretty jQuery-centric around here, but it's definitely not the only kid on the block. Thanks @mootools!