添加文本溢出:省略号;到 table 个单元格

Add text-overflow: ellipsis; to table cell

我在 table 中包含文本时遇到问题。我想给它一个text-overflow: ellipsis。但我似乎无法让它工作。

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;
}

虽然这不起作用。如果文本太长,它仍然会增加 td 的大小

您需要 table-layout: fixed 以及为 table 设置的宽度。否则省略号只能使用固定的 td 宽度。并将 white-space: normal 的值更改为 nowrap.

看来,你的table结构也需要修复,<thead>中缺少<tr>,最好在<thead>下面添加<tbody>

.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>

省略号不适用于:% (.article-table td > width: 20%; - 是你的问题)。

当我想以某种方式将“%”保留到 div 时,我的技巧是添加 2 个不同的维度:

max-width:300px; /*Inspect element in broswer and see how many pixels is 20%*/
width: 20%;

在这种情况下,省略号有效,我的 div、td 具有我想要的尺寸。

并为 .article-table td class:

试试这个
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;

在您的 td 标签内放置一个 div 并将样式应用于 div 将实现文本溢出:省略号;因此无需对 table.

应用固定布局

您还可以指定要在 ... 省略号生效之前分配多少行。

CSS

.max-lines-2 {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

HTML

<table style="width: 100%">
  <thead>
    <tr>
      <th style="width: 25%"></th>
       <!-- add your table headers with the desired width -->
    </tr>
  </thead>
  <tbody>
    <tr>
       <td><div class="max-lines-2"></div></td>
       <!-- add your table divs with the desired width -->
    </tr>
  </tbody>
 </table>