Skip to content
Advertisement

Replace too long strings with “…”

Lets say we have a <div style="width:100px;">This text is too long to fit</div>

The text in the div is dynamic. And I’d like to force the text to fit in width and not break. So i need some kind of functionality to test if the text is going to fit, and if it is not, then i’d like to display the portion of the text that will actually fit. And append ...to the end.

Result for a too long text should be something like this: "This text is..."

Is there some standard way of doing what i want? Either by javascript, jquery, jsp or java?

Thanks!

Edit: Thanks for your quick and many answers! I was doing this in java by guessing how many characters would fit. It seemed like a less than optimal solution, so thats why i came here.

The css solution is perfect for me. Its not that big of a deal that it doesnt work for firefox, since my clients all use ie anyway. 🙂

Advertisement

Answer

you could do it with css3 using text-overflow:ellipsis http://www.css3.com/css-text-overflow/

or if you insist on using the js way, you can wrap the text-node inside your div and then compare the width of the wrap with the with of the parent.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement