开发者

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

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>
      开发者_C百科  <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.


This is quite old but here is my answer.

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

DEMO


Try this on the span tag inside td

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

(late but might help someone else)


You don't have to specify the cell size in pixels, you can simply use percentages:

td.nowrap {
 overflow: hidden;
 white-space: nowrap;
 width: 60%;  /* or whatever */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜