Question

I'm looking for a technique (javascript, CSS, whatever ???) that will let me control the amount of a string that is displayed. The string is the result of a search (and therefore not initially known). A simple Character count approach is trivial, but not acceptable, as it needs to handle proportional fonts. In otherwords if I want to limit to say 70 pixels then the examples below show different character counts (9 and 15) both measuring the same:-

Welcome M...
Hi Iain if I've ...

If you look at Yahoo search results they are able to limit the length of title strings and add ellipsis on the end of long strings to indicate more. (try site:loot.com wireless+keyboard+and+mouse to see an example of Yahoo achieving this)

Any Ideas?

Was it helpful?

Solution

Perhaps the CSS property overflow: hidden; can help you, in conjuntion with width.

OTHER TIPS

Using a span with fixed width, overflow-x:hidden and white-space:nowrap would be a start.

To get the elipsis in a cross browser scenario will be difficult. IE has text-overflow:elipsis but that is non-standard. This is emulated with -o-text-overflow in Opera. However mozilla doesn't have this. The yahoo Javascript APIs handle this.

Yahoo does this server-side, the truncation and elipsis ('...') is returned in the HTML. Presumably this is done on a character count, and if thats not an option for you then server-side is out.

Other than overflow: hidden I'm not sure CSS can help you here. You could measure the width of the containing element using Javascript, and truncate the text based on that. This could be used in conjunctin with overflow:hidden; so the text elements don't just resize all of a sudden, but you may have to extract the text and add a temporary element onto the page somewhere to do the measurement. Depending on the number of elements to truncate this might not work very well.

Another slightly hacky option is to measure the width of an element containing the letter 'W', then do a character count and truncate if (char_count * width_of_w) > desired_width.

You can use text-wrap: none; to stop text wrapping onto new lines, although this is a CSS3 property and last I checked was only supported by IE (imagine my shock when I found that one out!).

For a cross-browser pure-CSS solution, take a look at Hedger Wang's text-overflow:ellipsis prototype, here:

http://www.hedgerwow.com/360/dhtml/text_overflow/demo2.php

In CSS: .class-name{ width: 5em; white-space: nowrap; text-overflow: ellipsis; }

Hope it can help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top