Hello!
After reading through your question, it seems that what you're asking is more JavaScript-related than CSS or HTML; It's not possible to do what you're asking with HTML, or CSS.
Below you'll see some JavaScript that should serve as a solution:
function isOverflowing(textWrapperDiv) {
let divOverflow = textWrapperDiv.style.overflow
if (!divOverflow || divOverflow === "visible") {
textWrapperDiv.style.overflow = "hidden"
}
let overflowStatus = textWrapperDiv.clientWidth < textWrapperDiv.scrollWidth || textWrapperDiv.clientHeight < textWrapperDiv.scrollHeight
textWrapperDiv.style.overflow = divOverflow
return overflowStatus
}
Note: Below, you'll want to change "YOUR-TEXT-WRAPPER-DIV-ID" to the id of the div that contains the text. If this is a different tag than div that's fine, div is just assumed for this example.
const div = document.getElementById("YOUR-TEXT-WRAPPER-DIV-ID")
const incrementionRate = 1
function changeFontByFill(textWrapperDiv) {
textWrapperDiv.style.fontSize = "1px"
let fitted = false
let lastSize
while (!fitted) {
if (isOverflowing(textWrapperDiv)) {
textWrapperDiv.style.fontSize = `${lastSize - incrementionRate}px`
fitted = true
}
else {
lastSize = parseFloat(textWrapperDiv.style.fontSize.slice(0, -2) + incrementionRate
textWrapperDiv.style.fontSize = `${lastSize}px`
}
}
}
adjustFontSize(div)
The above should adjust your element's (el) font-size to be just-before overflow. You'll need to have it execute in some way though, for this I'd encourage an event listener that runs changeFontByFill function if the user presses a "submit"/"save"/"update" button of some kind. This would look like:
window.addEventListener('click', function(){changeFontByFill(div)}, false);
Hopefully this helps! If you have any questions or concerns, please don't hesitate to respond or reach out.