How to automatically resize text in a fixed DIV according to the length of the text?

I have a fixed DIV width and height, and I need to put the text inside. The problem is that this text can be of different lengths (spelling), so I do not mind reducing its size after it is full.

But how can I do this?

thank

+3
javascript jquery html fonts
Nov 09 2018-10-11T00:
source share
2 answers

You can use window.getComputedStyle if you are targeting modern browsers.
It returns a collection of all real-style properties applied to the element.

When you assign your text, you can get its size and compare it with the size of the div. Reduce or increase the font size and measure again.
In several loops you should get the text in a DIV.

Here is the description: https://developer.mozilla.org/en/DOM:window.getComputedStyle

+3
Nov 09 2018-10-11T00:
source share

In short, you cannot do this because different platforms and browsers create fonts differently.

And there is no cross-browser cross-platform method for calculating font sizes.

Javascript "solution" is to check if the div overflows and then increase its size, something like

 while (div.scrollHeight >= div.offsetHeight) { div.style.height = (parseInt(fontSpan.style.fontSize) + 1) + 'px'; } 
+1
Nov 09 '10 at 8:53
source share



All Articles