I'm looking for a way to autoresize the text inside a div to its maximum size. The maximum size is the biggest size possible while still fitting the div.
I know it's not possible to do this in CSS. Is it possible with the use of javascript?
I'm looking for a way to autoresize the text inside a div to its maximum size. The maximum size is the biggest size possible while still fitting the div.
I know it's not possible to do this in CSS. Is it possible with the use of javascript?
You can use such trick in pure JavaScript to "auto resize" the font size:
window.onload = function() {
var oDiv = document.getElementById("Div1");
oDiv.style.overflow = "auto"; //for Firefox, but won't ruin for other browsers
var fontSize = 14;
var changes = 0;
var blnSuccess = true;
while (oDiv.scrollWidth <= oDiv.clientWidth) {
oDiv.style.fontSize = fontSize + "px";
fontSize++;
changes++;
if (changes > 500) {
//failsafe..
blnSuccess = false;
break;
}
}
if (changes > 0) {
//upon failure, revert to original font size:
if (blnSuccess)
fontSize -= 2;
else
fontSize -= changes;
oDiv.style.fontSize = fontSize + "px";
}
};
Start with the actual font size of the <div>
if you know it, otherwise better use smaller number as the first number.
The above code works on the principle that when the text is bigger than the set width of its container, the scrollWidth
property which is the "actual" width will be bigger than the set width.
Edit: Firefox won't update the scrollWidth
property if the overflow
CSS property is set to its default "visible" value, so you must set it to "auto" - the code is doing it for you, but also possible setting it via CSS if you prefer.