5

I want to ellipsify the text in the second column without hard-coding a width for either of the two columns. Is this possible where only the parent element (table) has a fixed width?

table {
  width: 100px;
  border: 1px solid green;
}

.td1 {
  border: 1px solid blue;
 }

.td2 {
  border: 1px solid red;
 }

.td div {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<table>
  <tr>
    <td class="td1">Label:</td>
    <td class="td2"><div>thequickbrownfoxjumpsoverthelazydog</div></td>
  </tr>
</table>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53

2 Answers2

5

You can do that within a nested table, I use a CSS table for the example, and added a span tag into the div for the table layout.

jsFiddle

table {
  width: 200px;
  border: 1px solid green;
}
.td1 {
  border: 1px solid blue;
}
.td2 {
  border: 1px solid red;
}
.td2 div {
  display: table;
  table-layout: fixed;
  width: 100%;
}
.td2 span {
  display: table-cell;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<table>
  <tr>
    <td class="td1">Label:</td>
    <td class="td2">
      <div><span>thequickbrownfoxjumpsoverthelazydog</span></div>
    </td>
  </tr>
</table>
Stickers
  • 75,527
  • 23
  • 147
  • 186
1

You need table-layout: fixed;

More info - https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout

The CSS for the ellipsis part is ok, but what happens is that, by default, a table calculates its width based on the content width, so the table cell would be as wide as the content, and the text would never be collapsed. table-layout: fixed; changes that. It means the table will calculate the dimensions of the cells before inserting the content, then the content will not affect the table's dimensions when rendered.

The tradeoff is that your table will no longer balance the columns automatically:

table {
  width: 100px;
  border: 1px solid green;
  table-layout: fixed;
}

.td1 {
  border: 1px solid blue;
 }

.td2 {
  border: 1px solid red;
 }

td div {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<table>
  <tr>
    <td class="td1">Label:</td>
    <td class="td2"><div>thequickbrownfoxjumpsoverthelazydog</div></td>
  </tr>
</table>
Hugo Silva
  • 6,748
  • 3
  • 25
  • 42