3

I have a fixed width and height DIV, and I need to put text inside. Problem is, this text can be in different lengths (letter-wise), so I dont mind to reduce its size once its overflowing.

But how can I do that?

Thanks

Himberjack
  • 5,682
  • 18
  • 71
  • 115

2 Answers2

3

You can use window.getComputedStyle if you target modern browsers.
It returns a collection of all real style properties applied to an element.

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

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

Mic
  • 24,812
  • 9
  • 57
  • 70
1

Long story short, you can't do it, since various platform and browsers render fonts differently.

And, there's no cross-browser, cross-platform method to calculate the font's rendered dimensions.

A Javascript "solution" is to check if the div is overflowing, and then bump up its size accordingly, something like

while (div.scrollHeight >= div.offsetHeight) {
    div.style.height = (parseInt(fontSpan.style.fontSize) + 1) + 'px';
}
Ben
  • 54,723
  • 49
  • 178
  • 224