首页 > 解决方案 > 限制两个 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。

标签: javascripthtmlcss

解决方案


使用一些 flexboxmax-height一个放置省略号的技巧,您可以使用纯 CSS 来实现这一点。

截屏:

代码截图

在 Codepen 上查看。

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


推荐阅读