views:

1142

answers:

6

Hi everyone!

I'm making a list of recent news. So, it will show something like this:

- Take a look at the new Volks...
- John Doe is looking for a jo...
- Microsoft is launching the n...

So, the list above only shows me the title of the news and the length of each news is limited in 25 characters. But, this is not working well... for example, if you type 25 M's, it will explode my div.

I've been told that there is a way to calculate the length of the string and make it fit in a div automatically.

Does anyone know how to do it?

thanks!!

+1  A: 

I think you want to use css for this.

word-wrap:break-word;

should do it

Greg Dean
This is about truncation, not wrapping. Text-overflow is the only css property that would do this, but is not well supported. Javascript or server-side solutions would be better.
Adam Lassek
+1  A: 

One very simple way to prevent "exploding the div" is to use a css style to set the overflow of the div to scroll or hide the extra text instead of stretching to accomodate it.

Joel Coehoorn
A: 

I don't think there is an easy way to do this that works with all browsers and fonts. The best way is just making sure your layout don't break if someone enters 25*m.

An useful thing to do is to split words that are more than X letter. I the word-wrap css don't work that well on all browers.

AndreasN
+1  A: 

I think you talking about is using the System.Drawing.Gaphics class's MeasureString() method.

However, this requires making a Graphics object which matches the font characteristics of your web page. But, your server process shouldn't know anything about the style elements of the web page, which should be handled by the CSS sheet.

James Curran
James, what I need is more like you told... Do you know how to use it?
AndreMiranda
+3  A: 

"text-overflow: ellipsis" is what you want but not everybody supports it. More info here...

David
A: 

This is not really a server-side problem, as the server shouldn't know what fonts people are using. You can do it using Ajax - post the font to the server, calculate the width (as James Curran mentioned), and return the right strings. However, the server may ont have the same fonts installed, and you have to calculate padding and margins on the server side.

I can think of several options on the client side:

  1. Wrap every line with a span. A span would expand automatically to the width of the line. Using jQuery or your favorite javascript you can remove characters until the width is ok. (you can do a sort of binary search, where at every stage you add the ellipsis and checks the width)
  2. Easy - Wrap every line with a fixed-width div and set it overflow:hidden, and add the ellipsis after the div. This will cut through letters though, and when you get a short text it'll still show the ellipsis.
  3. Too easy - Use a fixed width font (they're mostly ugly).
Kobi