Auto Filling Fonts

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.


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 ='line-spacing');
           if(linespacing==0 || linespacing==null) {
           } else {
               linespacing = parseFloat(linespacing);
               'font-size': Math.floor(fontSize)+'px',
               'line-height': (Math.floor(fontSize)*linespacing)+'px'
           if(fontSize-Math.floor(fontSize)>0.5) {

View extended jsFiddle version


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: