Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate text to fit table cell without wrapping using css or jquery

Tags:

jquery

css

I want the text in one of the columns of a table to not wrap, but to just truncate so that it fits within the current size of the table cell. I don't want the table cell to change size, as I need the table to be exactly 100% the width of the container.

This is because the table with 100% width is inside of a positioned div with overflow: auto (it's actually inside of a jQuery UI.Layout panel).

I tried both overflow: hidden and the text still wrapped. I tried white-space: nowrap, but it stretched the table wider than 100% and added a horizontal scroll bar.

div.container {
  position: absolute;
  overflow: auto;
  /* user can slide resize bars to change the width & height */
  width: 600px;  
  height: 300px;
}
table { width: 100% }
td.nowrap {
  overflow: hidden;
  white-space: nowrap;
}
<div class="container">
  <table>
    <tr>
      <td>From</td>
      <td>Subject</td>
      <td>Date</td>
    </tr>
    <tr>
      <td>Bob Smith</td>
      <td class="nowrap">
        <strong>Message subject</strong>
        <span>This is a preview of the message body and could be long.</span>
      </td>
      <td>2010-03-30 02:18AM</td>
    </tr>
  </table>
</div>

Is there a way using CSS to solve this? If I had a fixed table cell size, then overflow:hidden would truncate anything that flows over, but I can't used a fixed size as I want the table to stretch with the UI.Layout panel size.

If not, then how would I solve this with jQuery?

My use case is similar to the Gmail interface, where an email subject is bolded and the beginning of the message body is shown, but then truncated to fit.

like image 711
Tauren Avatar asked Mar 30 '10 09:03

Tauren


2 Answers

This is quite old but here is my answer.

table { width: 100%; table-layout: fixed;}

DEMO

like image 104
nyzm Avatar answered Sep 30 '22 01:09

nyzm


Try this on the span tag inside td

display: block;
word-break: break-all;

(late but might help someone else)

like image 31
minas Avatar answered Sep 30 '22 01:09

minas