JSFiddle - React, Tailwind, and code Playground

by ShaCP

HTML

<!-- <div id="container"><p>000 0</p></div> -->
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href='index3.css'>
    <script src="index3.js"></script>
</head>

<body>
    <p id="text"></p>
</body>

</html>

JavaScript

window.addEventListener("load", function () {
  var text = " Muhammad Ali ";
  var selection = window.getSelection();
  var textElement = document.getElementById("text");
  var textElementStyle = getComputedStyle(textElement);
  var maxWidth = parseFloat(textElementStyle.maxWidth);
  textElement.textContent = text;
  selection.selectAllChildren(textElement);
  var range = getSelection().getRangeAt(0);
  var boundingRect = range.getBoundingClientRect();
  var boundingRectWidth = boundingRect.width;
  var textElementFontSize = parseFloat(textElementStyle.fontSize);
  checkWidthAndAdjustFontSize();
  function checkWidthAndAdjustFontSize() {
    debugger;
    if (boundingRectWidth > maxWidth) {
      // textElement.style.overflowWrap = 'break-word';
      textElement.style.fontSize = `${--textElementFontSize}px`;
      boundingRect = range.getBoundingClientRect();
      boundingRectWidth = boundingRect.width;
      checkWidthAndAdjustFontSize();
    }
  }
  textElement.style.width = `${boundingRectWidth}px`;
});