ahelenius
ahelenius

Reputation: 70

How to get a non-fixed table cell to show ellipsis

I have an interesting CSS question for some of you CSS wizards. I have a table that has user generated content, and I want to limit long columns to a maximum width. The table is not fixed layout, and the column widths are user-specified too but by default should have a maximum width.

<table>
  <thead>
    <tr><td>Header 1</td><td>Header 2</td></tr>
  </thead>
  <tbody>
    <tr><td>Text</td><td>1</td></tr>
    <tr><td>Text</td><td>2</td></tr>
    <tr><td>Long Text Here</td><td>3</td></tr>
  </tbody>
</table>

I added overflow: hidden, white-space: nowrap, and text-overflow: ellipsis to the header's css class, and in the above html the text 'Long Text Here' pushes the width of that column out. But this makes it so that the column width can only be that text length or longer.

What can I do - other than use fixed layout - to make a cell shrink, and show ellipses?

Thanks!

Upvotes: 0

Views: 343

Answers (2)

Harry Cutts
Harry Cutts

Reputation: 1414

A simple option would be to set a maximum width on the column, so that a few really long entries don't make it ludicrously wide. For example, to do this for the first column:

td:first-child {
  max-width: 5em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<table>
  <thead>
    <tr><td>Header 1</td><td>Header 2</td></tr>
  </thead>
  <tbody>
    <tr><td>Text</td><td>1</td></tr>
    <tr><td>Text</td><td>2</td></tr>
    <tr><td>Really, Ridiculously Long Text Here</td><td>3</td></tr>
  </tbody>
</table>

(You could use :nth-child(), or maybe classes, to restrict other columns.)

This solution requires the maximum width to be set in the CSS, however, which might not be very useful for dynamic content. Instead, you could set it in style attributes in the HTML directly, which is easier to do using JavaScript or your templating system:

td:first-child, th:first-child {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<table>
  <thead>
    <tr><th style="max-width: 5em">Header 1</th><th>Header 2</th></tr>
  </thead>
  <tbody>
    <tr><td style="max-width: 5em">Text</td><td>1</td></tr>
    <tr><td style="max-width: 5em">Text</td><td>2</td></tr>
    <tr><td style="max-width: 5em">Really, Ridiculously Long Text Here</td><td>3</td></tr>
  </tbody>
</table>

Upvotes: 1

marcos.efrem
marcos.efrem

Reputation: 767

Hi I am not sure if you are asking for something like this

https://jsfiddle.net/MAXXALANDER/o6x1nt93/15/

table{
  width:100%;
}
td {
  width:50%;
  float:left; 
  padding:0; 
  margin:0; 
  text-overflow:ellipsis;
  white-space:nowrap;
  overflow:hidden;
}

Upvotes: 0

Related Questions