Dynamically change the size of the font size based on text length
css, html, javascript
Solution
Based on the logic of the top answer here, I created a no-jQuery version,
const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');
function resize_to_fit() {
let fontSize = window.getComputedStyle(output).fontSize;
output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
if(output.clientHeight >= outputContainer.clientHeight){
resize_to_fit();
}
}
function processInput() {
output.innerHTML =this.value;
output.style.fontSize = '100px'; // Default font size
resize_to_fit();
}
input.addEventListener('input', processInput);
<input type="text" placeholder="Add text input here" style="margin: 10px; width:50%;">
<div id="outer" class="container"
style="width:80%; height:100px; border:2px solid red; font-size:20px;">
<div class="output" style="word-break: break-all; word-wrap: break-word;">
</div>
</div>
Problem
I need to display user entered text into a fixed size div. What I want is for the font size to be automatically adjusted so that the text fills the box as much as possible. I'd probably want to start with a maximum font size and while the text is too big to fit the container, shrink the font size until it fits and the font must be displayed as a single line.