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:
1 2 3 | < div class = "ribbon-front" > < span >This is my text !</ span > </ div > |
The related CSS code:
1 | .ribbon-front { overflow : hidden } |
And the JavaScript code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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.
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
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…