Himberjack
Himberjack

Reputation: 5802

How to auto resize text in fixed DIV according to the text's length?

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

Upvotes: 3

Views: 4081

Answers (2)

Ben
Ben

Reputation: 57318

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';
}

Upvotes: 1

Mic
Mic

Reputation: 25184

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

Upvotes: 3

Related Questions