2

I have a table with columns that have percentage widths. If the content within those cells exceeds that percentage width, I would like it to be truncated with an ellipsis.

According to CSS text-overflow in a table cell? I should use the max-width attribute, but according to How can I set the max-width of a table cell using percentages? I can't do it with percentages.

table {
  width: 100%;
}
table td {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
table tr td:nth-of-type(1) {
  width: 20%;
}
table tr td:nth-of-type(2) {
  width: 30%;
}
table tr td:nth-of-type(3) {
  width: 50%;
}
<table>

  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>

  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>

</table>

How can I resolve this?

Community
  • 1
  • 1
Jack Guy
  • 8,346
  • 8
  • 55
  • 86

2 Answers2

9

This cannot work with a standard HTML table: the automatic layout algorithm will keep stretching cells so they can always fit their contents, even ignoring explicit widths.

Switch to table-layout:fixed and everything will work as intended.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • Works great! Make sure you don't have a min-width on the table applied somewhere else in the code... – Kraken Dec 11 '20 at 12:25
0

layout: fixed doesn't work for all situations, and the table should be fluid and auto-space its cells, which also means setting 1% for certain cells and having others automatically adjust.

Use this: http://jsfiddle.net/maruxa1j/

Works on IE9+ too.

anthumchris
  • 8,245
  • 2
  • 28
  • 53