I settled for the limitation (to some people a benefit) of having my rows only one line of text high. The CSS to contain long strings then becomes:
.datatable td {
overflow: hidden; /* this is what fixes the expansion */
text-overflow: ellipsis; /* not supported in all browsers, but I accepted the tradeoff */
white-space: nowrap;
}
[edit to add:] After using my own code and initially failing, I recognized a second requirement that might help people. The table itself needs to have a fixed layout or the cells will just keep trying to expand to accomodate contents no matter what. If DataTables styles or your own styles don't already do so, you need to set it:
table.someTableClass {
table-layout: fixed
}
Now that text is truncated with ellipses, to actually "see" the text that is potentially hidden you can implement a tooltip plugin or a details button or something. But a quick and dirty solution is to use JavaScript to set each cell's title to be identical to its contents. I used jQuery, but you don't have to:
$('.datatable tbody td').each(function(index){
$this = $(this);
var titleVal = $this.text();
if (typeof titleVal === "string" && titleVal !== '') {
$this.attr('title', titleVal);
}
});
DataTables also provides callbacks at the row and cell rendering levels, so you could provide logic to set the titles at that point instead of with a jQuery.each
iterator. But if you have other listeners that modify cell text, you might just be better off hitting them with the jQuery.each
at the end.
This entire truncation method will ALSO have a limitation you've indicated you're not a fan of: by default columns will have the same width. I identify columns that are going to be consistently wide or consistently narrow, and explicitly set a percentage-based width on them (you could do it in your markup or with sWidth). Any columns without an explicit width get even distribution of the remaining space.
That might seem like a lot of compromises, but the end result was worth it for me.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…