Search code examples
htmlcsshtml-tableellipsis

Add text-overflow: ellipsis; to table cell


I'm having trouble containing text in a table. I want to give it a text-overflow: ellipsis. But I can't seem to get it to work.

HTML:

<table class="article-table">
  <thead class="article-table__headers">
    <th>Title</th>
    <th>Source</th>
    <th>Abstract</th>
    <th>Folder</th>
  </thead>
  <% @articles.each do |article| %>
    <tr class="article-table__rows">
      <td><%= article.title %></td>
      <td><%= article.source %></td>
      <td><%= article.abstract %></td>
      <td><%= article.folder %></td>
      <td><%= link_to "Download File", download_article_path(article) %></td>
    </tr>
  <% end %>
</table>

CSS:

.article-table td {
    width: 20%;
    border-bottom: 1px solid #ddd;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: normal;
}

This isn't working though. it still increases the size of the td if text is too long


Solution

  • You will need table-layout: fixed along with width set for the table. Otherwise ellipsis can only work with fixed td width. And change the value of white-space: normal to nowrap.

    Looks like, your table structure also needs to be fixed, missing <tr> in <thead>, and better to add <tbody> below <thead>.

    .article-table {
      table-layout: fixed;
      width: 100%;
    }
    
    .article-table td {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    <table class="article-table">
      <thead>
        <tr>
          <th>Title</th>
          <th>Source</th>
          <th>Abstract</th>
          <th>Folder</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>The quick brown fox jumps over the lazy dog</td>
          <td>The quick brown fox jumps over the lazy dog</td>
          <td>The quick brown fox jumps over the lazy dog</td>
          <td>The quick brown fox jumps over the lazy dog</td>
        </tr>
      </tbody>
    </table>