tags:

views:

60

answers:

1

I'm trying to truncate a string to a certain pixel width. The best way I discovered is through using jQuery's selector and possibly using each on the results. My attempt is at http://jsbin.com/umawi/edit. I haven't done much jQuery at all, and any help is appreciated.

Thanks

Edit: I need to do this for inline elements and not block elements.

+3  A: 

You don't need jquery for this.

<div class="truncate">Truncate some test</div>

with:

div.truncate { width: 100px; white-space: nowrap; overflow: hidden; }

as just one simple example. You can even add:

text-overflow: ellipsis;

but support is limited.

It's also worth noting that this only works (well) on block display elements, not inline and not table cells so if this is in a table you'll need to do:

<td><div>...</div></td>

because otherwise you won't get the desired results.

cletus
Thanks a bunch. I tried this before, but didn't know I needed the nowrap and hidden overflow.
Simon
What if I want to do this to inline elements? Say, a part of an unordered list? Is there a better way to do this?
Simon
List elements aren't inline. But no you can't apply overflow to inline (well you can, it just won't do what you want).
cletus