Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

html - How can I truncate long texts in a table using CSS?

Can anyone give a CSS example of how can I create a table where long texts are truncated to texts ending with "..."?

Here is the example: http://jsfiddle.net/NpABe/

<table>
    <tr>
        <td>aaaa</td>
        <td>ssssssss</td>
        <td>dddddddddddd</td>
    </tr>
    <tr>
        <td>ffffffffffffffff</td>
        <td>gggggggggggggggggggg</td>
        <td>hhhhhhhhhhhhhhhhhhhhhhhh</td>
    </tr>
    <tr>
        <td>jjjjjjjjjjjjjjjjjjjjjjjjjjjj</td>
        <td>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</td>
        <td>llllllllllllllllllllllllllllllllllll</td>
    </tr>
</table>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use text-overflow: ellipsis. You will need to fix the width of the cells and prevent line wrapping:

td {
  width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

EDIT: actually this won't work. It seems you need a container div to apply the styles to:

<table>
  <tr>
    <td><div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div</td>
(snip)

And then:

 td div {
   width: 100px;
   white-space: nowrap;
   overflow: hidden;         
   text-overflow: ellipsis;
 }

EDIT 2 Ah there is a way, but only if you use table-layout: fixed:

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

td {
  white-space: nowrap;
  overflow: hidden;         /* <- this does seem to be required */
  text-overflow: ellipsis;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...