首页 > 解决方案 > 在文本块中保留换行符,但限制为一行

问题描述

我有一个表,该表中的每一行都有一个描述,该描述可能类似于:

This is an example:
    - Example 1
    - Example 2
    - Example 3

现在我想将描述限制为 1 行,溢出:隐藏在其上,并保留换行符,这样无论什么- Example 1都不会显示。

如果可能的话,我想用纯 CSS + HTML 来做这件事。

我已经尝试过以下方法:

.overflowing-description {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: pre-line;
    max-height: 30px;
    max-width: 20%;
}

max-width 和 max-height 都没有做任何事情,所以我假设它在white-space: pre-line这里覆盖了一些东西。

jsbin 示例: https ://jsbin.com/nowuxot

th, td {
  padding: 15px;
  text-align: left;
  border: 1px solid #ddd;
}
th {
  border-bottom: 1px solid;
}
table {
  width: 100%;
  border-collapse: collapse;
}

.overflowing-description {
  text-overflow: ellipsis;
  max-height: 20px;
  overflow: hidden;
  white-space: pre-line;
  max-width:5%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
 <table>
   <thead>
     <tr>
       <th>
         name
       </th>
       <th>
         price
       </th>
       <th>
         description
       </th>
     </tr>
   </thead>
   <tbody>
   <tr>
     <td>
       Example
     </td>
     <td>
       123
     </td>
     <td class="overflowing-description">
       asd asd asd asd 
       asd
       asd
       asd
     </td>
   </tr>
   <tr>
     <td>
       Example
     </td>
     <td>
       123
     </td>
     <td class="overflowing-description">
       asd asd asd asd 
       asd
       asd
       asd
     </td>
   </tr>
   <tr>
     <td>
       Example
     </td>
     <td>
       123
     </td>
     <td class="overflowing-description">
       asd asd asd asd 
       asd
       asd
       asd
     </td>
   </tr>
 </table>
</body>
</html>

标签: htmlcss

解决方案


一条评论 - 你不能改变高度td。将文本放入p

<td><p class="overflowing-description">asd asd asd asd</p></td>

其次,这足以隐藏下一行并保留换行符:

.overflowing-description {
    max-height: 1rem;
    overflow: hidden;
    white-space: pre-line;
}

至于显示省略号,我曾经看到一个使用 JavaScript 自动添加它的解决方案,但纯 CSS 也有一些可能性。看到那个链接

更新

还有一个“草稿” CSS 属性可以做到这一点,而且它似乎得到了很好的支持:-webkit-line-clamp.

更多内容在MDN中。


推荐阅读