Autosize a text to fit into a div in pure/native JavaScript

I was looking for a very tiny and light solution to fit a text inside a box. The box’ height and width are fixed. I only found some great solutions like BigText but I didn’t want to have jQuery loaded.

Finally I found some code on StackOverflow and also at Coderwall. I created my own solution that could only work with my own HTML code… but I share it here, maybe that could help someone else.

The HTML code:

  
This is my text !

The related CSS code:

.ribbon-front { overflow:hidden }

And the JavaScript code:

var autoSizeText = function(selector) {
  "use strict";
  var el, elements, i, len, style, fontSize, IEoffsetHeight;
  elements = document.querySelectorAll(selector);
  if (elements.length <= 0) return;
  
  for (i=0, len = elements.length; i < len; i++) {
    el = elements[i];

    // we start from 0px and we grow by 0.5 until the content is too large
    fontSize=0;
    el.style.fontSize = "0px";
    // fix for all IE : I cache the offsetHeight, and if it becomes really bigger than the previous value, then we stop!
    IEoffsetHeight = el.offsetHeight;
    // check if our content is out its box
    while (el.scrollHeight===0 || el.scrollHeight >= el.offsetHeight) {
      fontSize += 0.5;
      el.style.fontSize = fontSize + 'px';

      if (el.offsetHeight - IEoffsetHeight > 10) break;
      IEoffsetHeight = el.offsetHeight;
    }
    el.style.fontSize = (fontSize - 0.5) + 'px';
  }
};
autoSizeText('.ribbon-front > span');

It works for IE8-IE10 and with all modern browsers.

You can see a demo at codepen.

2 avis sur “Autosize a text to fit into a div in pure/native JavaScript

  1. Carlos

    WOW.. thanks for the great script.. really COOL!!

    There is one small bug that I can’t get around though.. if my string under the span tag only contains one single word, I get an infinite loop and my page doesn’t load

  2. Aymeric Auteur de la publication

    I ran a few tests, and indeed that doesn’t work with only one word…. It seems more like a browser bug I think. I tried a few things without success…

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*