I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)
Ba
I recently had a max width div that was receiving text from a text input field and I had to make the text fit in that div, so here is how I solved it (simple JS, no plugin):
function addName(){
let maxWidth = 550;
let defaultFontSize = 50;
let entry = document.getElementById('nameInput').value;
let nameDiv = document.getElementById('name');
let fontSize = nameDiv.style["font-size"];
fontSize = fontSize.replace('px','');
fontSize = parseInt(fontSize);
nameDiv.innerText = entry;
if (nameDiv.clientWidth > maxWidth) {
fontSize = fontSize - 2.5;
nameDiv.style["font-size"] = `${fontSize}px`;
} else if (nameDiv.clientWidth < maxWidth && fontSize < defaultFontSize ) {
fontSize = fontSize + 2.5;
nameDiv.style["font-size"] = `${fontSize}px`;
}
}
#name {
height: 70px;
line-height: 70px;
text-align: center;
overflow: hidden;
width: auto;
display: table; /*THAT DOES THE MAGIC*/
margin: auto;
border: 1px solid black
/* THE BORDER IS FOR TEST PURPOSES TO SEE WHAT'S HAPPENING WITH THE DIV*/
}