2

我们需要在最多 3 行上显示产品标题,并且只有当标题超过 3行时才会淡出第3 行。

到目前为止,我试图解决这个问题的方法是使用一个最大高度为 3 行的包装器、其中的标题和一个覆盖淡出(分别是淡入白)渐变的伪元素。

.title:after {
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 75%, rgba(255, 255, 255, 1) 100%);
  content: '';
  width: 100%;
  height: 1.3rem;
  position: absolute;
  top: 2rem;
  left: 0;
}

问题是,无论是否有第 4(+)行,都会发生这种情况。

我创建了一个 JSFiddle:https ://jsfiddle.net/nq4ratr7/5/

小提琴示例的目标是显示最多 3 行的所有标题而没有淡出,并在第 3 行淡出,用于中断到 4 的示例(“4 行 ...”)。

出于性能原因,不应使用 JS。我很清楚使用 JS 很容易。

4

1 回答 1

1

这需要一个带有溢出功能的容器。叠加层位于子元素内部,其高度源自calc(100% - (line-height × 3))- 这将产生一个负数(浏览器将其变为 0)、0 或超出的高度。然后我们使用一个固定的高度梯度,repeating-linear-gradient并将其向上移动 ( line-height)。

.holder {
    width: 275px;
}

.title {
    margin: 30px 0;
    max-height: 75px; /* line-height × 3 */
    overflow: hidden;
}

.title > h2 {
    position: relative;
    margin: 0;
    padding: 0;
    line-height: 25px;
    font-size: 18px;
}

.title > h2::after {
    content: '';
    display: block;
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: calc(100% - 75px); /* 100% - (line-height × 3) */
    transform: translateY(-25px); /* 0 - line-height */
    background: repeating-linear-gradient(rgba(255, 255, 255, 0), #ffffff 25px); /* line-height */
}
<div class="holder">
    <div class="title">
        <h2>1 line of text 1 line of text</h2>
    </div>
    <div class="title">
        <h2>2 lines of text 2 lines of text 2 lines of text 2 lines of text 2 lines of text</h2>
    </div>
    <div class="title">
        <h2>3 lines of text 3 lines of text 3 lines of text 3 lines of text 3 lines of text 3 lines of text 3 lines of text</h2>
    </div>
    <div class="title">
        <h2>4 lines of text 4 lines of text 4 lines of text 4 lines of text 4 lines of text 4 lines of text 4 lines of text 4 lines of text 4 lines of text 4 lines of text</h2>
    </div>
    <div class="title">
        <h2>5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text 5 lines of text</h2>
    </div>
    <div class="title">
        <h2>6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text 6 lines of text</h2>
    </div>
</div>

于 2018-05-02T15:03:48.460 回答