html - 在文本块中保留换行符,但限制为一行
问题描述
我有一个表,该表中的每一行都有一个描述,该描述可能类似于:
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>
解决方案
一条评论 - 你不能改变高度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中。
推荐阅读
- r - 如何通过自定义函数对列表进行排序,丢弃重复项?
- r - 总结连续数据,其中一个变量具有多个独特的观察值,而其他变量可以分组
- python - 分配前引用的变量“product_id”
- c++ - 为什么我不能更改实例化对象内部的向量?
- angular - 如何从另一个页面接收参数
- c - 为什么 sizeof(*pointer) 输出为 1?
- racket - 如何验证字符串的格式是否正确?
- python-3.x - 创建函数以返回多个数据帧
- css - 是什么导致了 Firefox 和 IE 上的列表项内的垂直错位,但在 Chrome 中却没有?
- linux - 将命令行参数打印到新的 Linux tex 文件中