The maximum size of the text inside the div

I am looking for a way to autoresist text inside a div to its maximum size. The maximum size is the largest size that is still suitable for a div.

I know that this cannot be done in CSS. Is this possible with javascript?

+1
source share
1 answer

You can use this trick in pure JavaScript to "automatically 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"; } }; 

Live test .

Start with the actual font size of the <div> if you know it, otherwise it’s better to use a lower number as the first number.

The above code works on the principle that when the text is larger than the specified width of its container, the scrollWidth property, which is the "actual" width, will be larger than the set width.

Edit:. Firefox will not update the scrollWidth property if the CSS overflow property is set to “visible” by default, so you must set it to “auto” - the code does this for you, but it is also possible to set it using CSS if you prefer.

+4
source

Source: https://habr.com/ru/post/1381020/


All Articles