Auto adjust font size

This is a demo for https://www.zhuwenlong.com/blog/article/528611f363c705fc73000001

by zhuwenlong

HTML

<h3>
This is a demo for <a href="https://www.zhuwenlong.com/blog/article/528611f363c705fc73000001" target="_blank">https://www.zhuwenlong.com/blog/article/528611f363c705fc73000001</a>
</h3>

<div style="height: 200px; border:1px solid #ccc;">
  <div class="box">
    Hello , I am Mofei
  </div>
</div>

<div style="height: 200px; border:1px solid #ccc;">
  <div class="box">
    Hello
  </div>
</div>

<div style="height: 200px; border:1px solid #ccc;">
  <div class="box">
    Hello , I am Mofei. Hello , I am Mofei Hello , I am Mofei Hello , I am Mofei Hello , I am Mofei Hello , I am Mofei Hello , I am Mofei
  </div>
</div>

JavaScript

// max height
const maxHeight = 200;
const wordboxs = document.body.querySelectorAll('.box');

// loop
for (var j = 0; j < wordboxs.length; j++) {
  const wordbox = wordboxs[j];
  // init the fontisze
  wordbox.style.fontSize = '12px';
  for (var i = 12; i < 200; i++) {
    if (wordbox.offsetHeight > maxHeight) {
      // if it's height heighter than thhe maxHeight
      wordbox.style.fontSize = (i - 2) + 'px';
      break;
    } else {
      // if it's height less then the maxHeight
      wordbox.style.fontSize = i + 'px';

    }
  }
}