Reputation: 2269
<table id="tab">
<tr><td>....</td><td>2222</td></tr>
<tr><td>@@@@</td><td>4444</td></tr>
</table>
#tab td {
border: solid 1px red;
max-width: 50px;
}
LIVE EXAMPLE: http://jsfiddle.net/mCxqD/
i would like cut text in TD if he is too long. I can use strlen and substr, but:
strlen(....) = 4; strlen(@@@@) = 4;
and in table occupy different amount of space.
How is the best way for this? I don't have wrap to new line. I would like somethings: http://jsfiddle.net/mCxqD/1/
edit: overflow:hidden is good, but what if i would like add for overflow text for example "*"? http://jsfiddle.net/7ksD7/2/
Upvotes: 2
Views: 695
Reputation: 71
This is a little round-about (and using jQuery... although you could do this with regular JS easily enough), but you could try using JS to wrap the text in a span tag and measure it while comparing against the max width. You might need to tweak a few things (e.g. - make sure that you compensate for the width of the character used to denote a cut-off), but I think this should work (if you don't have text-overflow available):
$(document).ready(function() {
$('td').each(function() {
var contents = $(this).html();
var max_width = $(this).css('max-width').replace('px', '');
var cut_char = '*';
$(this).html('');
$(this).append('<span>' + contents + '</span>');
var $span = $(this).find('span:first');
var content_width = $span.innerWidth();
while (content_width > max_width) {
var str = $span.html();
$span.html(str.substring(0, str.length - 1));
content_width = $span.innerWidth();
if (content_width < max_width) {
$span.html(str.substring(0, str.length - 2) + cut_char);
}
}
});
});
Here's your fiddle updated: http://jsfiddle.net/mCxqD/6/
Upvotes: 1
Reputation: 49225
I think your best bet would be text-overflow property -
#tab td {
border: solid 1px red;
max-width: 50px;
overflow:hidden;
white-space:nowrap;
text-overflow: ellipsis;
}
see http://jsfiddle.net/7ksD7/5/
See more here about the same - although this article says that the property is not supported on FF, at least my browser (FF 7) appears to support it.
Upvotes: 1