How to truncate table cells, but fit as much as content possible with CSS?

Spread the love

Sometimes, we want to truncate table cells, but fit as much as content possible with CSS.

In this article, we’ll look at how to truncate table cells, but fit as much as content possible with CSS.

How to truncate table cells, but fit as much as content possible with CSS?

To truncate table cells, but fit as much as content possible with CSS, we use the white-space property.

For instance, we write

<table border="1" style="width: 100%">
  <colgroup>
    <col width="100%" />
    <col width="0%" />
  </colgroup>
  <tr>
    <td
      style="
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 1px;
      "
    >
      This cell has more content.This cell has more content.This cell has more
      content.This cell has more content.This cell has more content.This cell
      has more content.
    </td>
    <td style="white-space: nowrap">Less content here.</td>
  </tr>
</table>

to make the content fit on 1 row with white-space: nowrap;.

We hide overflowing content with overflow: hidden;.

And we add an ellipsis after the truncated content with text-overflow: ellipsis;.

Conclusion

To truncate table cells, but fit as much as content possible with CSS, we use the white-space property.

Leave a Reply

Your email address will not be published. Required fields are marked *