Archive for Code Snippet

Auto Filling Fonts

Posted in Code Snippets with tags , , on February 12, 2013 by chrispikul510

So I needed some code that would automatically set a span’s font-size to one that would fill the width of its parent container. So I wrote one for jQuery. I’ve seen some other plugins and such, but instead of having to link in another source, I wrote one that can be housed in a single function.

The function searches for any and all spans that have the “autoFill” class on them and runs the calculations. It also searches for an optional data-line-spacing attribute that will modify the line spacing. By default the line-spacing is set to the same as the font size. The line-spacing attribute is expected to be a percentage float (0.0 – 1.0+). I chose this format because the sizing is meant to be dynamic, percentages seem more fitting.

JavaScript/jQuery:

function refreshAutoFill() {
    $('span.autoFill').each(function() {
       var elem = $(this);
       var par = $(this).parent();
       if(elem && par) {
           var fontSize = (par.width()/elem.width())*parseInt(elem.css('font-size'));
           var linespacing = elem.data('line-spacing');
           if(linespacing==0 || linespacing==null) {
               linespacing=1;
           } else {
               linespacing = parseFloat(linespacing);
           }
           elem.css({
               'font-size': Math.floor(fontSize)+'px',
               'line-height': (Math.floor(fontSize)*linespacing)+'px'
           });
           if(fontSize-Math.floor(fontSize)>0.5) {
               elem.css('letter-spacing','1px');
           }
       }
    });
}

View extended jsFiddle version

Advertisements