javascript - 限制两个 div 中的最大总行数
问题描述
我知道如何制作一个 div 以在n行之后使用省略号(在这种情况下 n 是 2 行):
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
它适用于一个div
,但我有一个不同的问题。我有一些内容的标题和描述,我想将这两个字段本身限制为最多 3 行,但总共也限制为 5 行(而不是可能的最大值,在这种情况下为 6 行)。换句话说,如果标题是 3 行,我想在两行(带有省略号)之后剪切描述。
我如何实现这一点(最好没有或使用最少的 Javascript)?我现在只需要支持(移动)Safari。
解决方案
使用一些 flexboxmax-height
和一个放置省略号的技巧,您可以使用纯 CSS 来实现这一点。
截屏:
:root {
--field-max-lines: 3;
--desc-max-lines: 2; /* if title reached maximum number of lines */
--title-lh: 30px;
--desc-lh: 20px;
font-size: 16px;
}
* {
margin: 0;
padding: 0;
}
body {
display: flex;
gap: 20px;
padding: 20px;
}
div {
display: flex;
flex-direction: column;
max-height: calc(var(--field-max-lines) * var(--title-lh) + var(--desc-max-lines) * var(--desc-lh));
width: 200px;
}
div>* {
overflow: hidden;
position: relative;
padding-right: 1rem;
}
div>*::before {
position: absolute;
content: "...";
bottom: 0;
right: 0;
}
div>*::after {
position: absolute;
content: "";
right: 0;
width: 1rem;
height: 1.5rem;
}
strong {
flex: none;
line-height: var(--title-lh);
max-height: calc(var(--field-max-lines) * var(--title-lh));
font-size: 20px;
}
strong,
strong::after {
background: red;
}
p {
line-height: var(--desc-lh);
max-height: calc(var(--field-max-lines) * var(--desc-lh));
}
p,
p::after {
background: yellow;
}
<div>
<strong>This title has 2 lines. This title has 2 lines.</strong>
<p>This description has 4 lines. This description has 4 lines. This description has 4 lines. This description has 4 lines.</p>
</div>
<div>
<strong>This title has 3 lines. This title has 3 lines. This title has 3 lines.</strong>
<p>This description has 2 lines. This description has 2 lines.</p>
</div>
<div>
<strong>This title has 3 lines. This title has 3 lines. This title has 3 lines.</strong>
<p>This description has 3 lines. This description has 3 lines. This description has 3 lines.</p>
</div>
<div>
<strong>This title has 4 lines. This title has 4 lines. This title has 4 lines. This title has 4 lines. This title has 4 lines.</strong>
<p>This description has 3 lines. This description has 3 lines. This description has 3 lines.</p>
</div>
推荐阅读
- amazon-web-services - AWS SAM 以及每次部署的资源 ARN 更改
- php - 无法从 laravel 中的主表中获取数据
- laminas - Laminas CollectionInputFilter - 验证最小/最大项目数
- java - 如何将控制台显示中的输出保存到 Java 中的文本文件中?
- java - Servlet 因 IOException 失败 weblogic.utils.NestedRuntimeException:无法解析请求的 POST 参数
- python - 动态地将参数传递给 objects.filter
- spring - 由于@JoinColumn(nullable = false),Spring/JPA 两次单向不起作用
- python - 如何比较两个光谱并匹配相似的吸收线?
- java - 带有 Runtime.getRuntime().exec() 的 Java 中的 Shell 命令;
- sql - BigQuery FIRST_VALUE() - 先返回空值,同时仍指示排序?