JSFiddle - React, Tailwind, and code Playground
HTML
<button onclick='addText(); resizeFont()'>Click Me to Add Some Text!</button>
<div id="output"></div>
CSS
div {
width: 160px;
height: 160px;
background: yellow;
}
JavaScript
function resizeFont() {
var output = document.querySelector('#output'),
numRE = /(\d+)px/,
height = numRE.exec(window.getComputedStyle(output).height)[1],
fontSize = height;
// allow div to be empty without entering infinite loop
if (!output.innerHTML.length) return;
// set the initial font size to the height of the div
output.style.fontSize = fontSize + 'px';
while (output.scrollHeight > height)
output.style.fontSize = --fontSize + 'px';
}
function addText() {
var text = "Lorem ipsum dolor amit",
len = Math.floor(Math.random() * 15),
output = document.querySelector('#output'),
str = [];
for (; --len;)
str.push(text);
output.innerHTML = str.join(', ');
}