JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Multiline mode test</h2>
<input type='text' placeholder='type some text...'/>
<div></div>
<h2>Single-line mode test</h2>
<span id='menu1'>Hoa cúc</span>
<span id='menu2'>Chrysanthemum</span>
CSS
div:not(.dummy) {
border:1px solid black;
width:100px;
height:50px;
word-wrap:break-word;
}
/* style the menus, they are supposed to have fixed width */
span {
border:1px solid black;
display:block;
width:100px;
height:1.2em;
}
JavaScript
console.clear();
var input = document.querySelector('input');
var div = document.querySelector('div');
input.oninput = function(){
div.innerHTML = this.value;
adjustFontSize(div, false);
};
var dummy = document.createElement('div');
dummy.className = 'dummy';
var inSingleLineMode, inMultilineMode;
//use it in single-line mode for the menus
adjustFontSize(menu1, true);
adjustFontSize(menu2, true);
//function used to adjust the font-size of the element
//so that the width is fixed (single-line mode) or both the width and height are
//fixed (multi-line mode), of course the text should be contained within the fixed width
//and height.
function adjustFontSize(element, singleLine){
if(!element.innerHTML) return;
var elementStyle = getComputedStyle(element);
dummy.style.font = elementStyle.font;
initMode(singleLine, function(){ dummy.style.width = elementStyle.width });
dummy.style.padding = elementStyle.padding;
dummy.style.boxSizing = elementStyle.boxSizing;
dummy.innerHTML = element.innerHTML;
document.body.appendChild(dummy);
var dummyStyle = getComputedStyle(dummy);
while(singleLine ? parseInt(dummyStyle.width) < parseInt(elementStyle.width) :
parseInt(dummyStyle.height) < parseInt(elementStyle.height)){
dummy.style.fontSize = parseFloat(dummyStyle.fontSize) + 1 + 'px';
dummyStyle = getComputedStyle(dummy);
}
while(singleLine ? parseInt(dummyStyle.width) > parseInt(elementStyle.width) :
parseInt(dummyStyle.height) > parseInt(elementStyle.height)){
dummy.style.fontSize = parseFloat(dummyStyle.fontSize) - 1 + 'px';
dummyStyle = getComputedStyle(dummy);
}
element.style.fontSize = dummyStyle.fontSize;
document.body.removeChild(dummy);
}
function initMode(singleLine, callback){
if(!dummy) return;
if(singleLine&&!inSingleLineMode) {
dummy.style.whiteSpace =...