Search code examples
javascriptcssstringhtmlfill

Fitting text into a fixed-size div


I have a fixed size div which I need to fill with text. I need to only fill it with as much text will fit into it, and I need to know the offset in the string where it cut off.

Right now I am doing it by saving the div's current height then setting the div's height to auto, taking increasingly long substrings of the string and putting them into the div, and stopping when the div's height gets bigger than the original height. This works, but it's pretty inefficient.

Is there any better way to do this? And by better I mean faster.


Solution

  • Well, I came up with this: http://jsfiddle.net/r5Njr/. That should fit the text into the div. If you want to be fancy, you can change the last 2 or 3 characters to a ...