There are many resize-to-fit-text scripts out there but I am proposing one small solution of mine instead of using a plugin to do this.

Let me show you a small demonstration of the script in slow motion:

So what is happening is the title has a certain font size and then we decrease that font size with 0.1rem and check again if it fits in it’s container. If it doesn’t we repeat our font size decrease again and again and again till it fits. In real life this happens very fast:

Next, I will provide you with the script:

const fitText = target => {
  document.querySelectorAll(target).forEach(el => {
    const initialSize = parseInt(window.getComputedStyle(el, null).getPropertyValue('font-size'), 10);
    const baseSize =  parseInt(window.getComputedStyle(document.body).getPropertyValue('font-size'), 10);
    const initialSizeInRem = (1 / baseSize) * initialSize;
    let decreasedSize = initialSize;
    while (el.scrollWidth > el.clientWidth) {
      decreasedSize -= 0.1;
      el.style.fontSize = `${decreasedSize}rem`

To call the fitText() plugin, you do the following:

addEventListener('resize', (event) => {

I applied the resize functionality on h1, h2 and h3 title tags. The script is used on load and also on resize of the window.

If you are interested in the explanation of the code, please read further 🙂

First of all the function iterates through the selectors that you gave as arguments. Then we take the initial font size of the title(in pixel) and in the while loop we check if the scrollable area(scrollWidth) of this title is bigger then it’s actual width(clientWidth), then it means that the title is overflowing it’s parent. If it does overflow, then we give the decreasedSize a new value(less with 0.1) and reduce it’s font size also with 0.1 pixel. After this the while loop checks again if the title is still overflowing it’s parent. If not, the while loop ends and the resizing stops.

Now the problem is that we would like to have the decreased font size in rem unit, for the sake of usability. We need to get the base font size of the body and convert the initial font size of the title from pixel to rem. The formula I used is this:

(1 / base font size ) * title font size in pixel

Of course the other formula works too:

title font size / base font size

As you can see in the end I gave the new font size with the rem unit.

I hope you enjoyed this small article and please like, comment and subscribe !

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in: