使用 CSS 将文本长度限制为 n 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3922739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:56:55  来源:igfitidea点击:

Limit text length to n lines using CSS

csstextoverflowellipsis

提问by Peter

Is it possible to limit a text length to "n" lines using CSS (or cut it when overflows vertically).

是否可以使用 CSS 将文本长度限制为“n”行(或在垂直溢出时将其剪切)。

text-overflow: ellipsis;only works for 1 line text.

text-overflow: ellipsis;仅适用于 1 行文本。

original text:

原文:

Ultrices natoque mus mattis, aliquam, cras in pellentesque
tincidunt elit purus lectus, vel ut aliquet, elementum nunc
nunc rhoncus placerat urna! Sit est sed! Ut penatibus turpis
mus tincidunt! Dapibus sed aenean, magna sagittis, lorem velit

Ultrices natoque mus mattis、aliquam、cras in pellentesque tincidunt
elit purus lectus、vel ut aliquet、elementum
nunc nunc rhoncus placerat urna!坐吧!Ut penatibus turpis
mus tincidunt!Dapibus sed aenean, magna sagittis, lorem velit

wanted output (2 lines):

想要的输出(2 行):

Ultrices natoque mus mattis, aliquam, cras in pellentesque
tincidunt elit purus lectus, vel ut aliquet, elementum...

Ultrices natoque mus mattis, aliquam, cras in pellentesque
tincidunt elit purus lectus, vel ut aliquet, elementum...

回答by Evgeny

There's a way to do it using unofficial line-clampsyntax, and starting with Firefox 68 it works in all major browsers.

有一种方法可以使用非官方的line-clamp语法来实现,从 Firefox 68 开始,它适用于所有主要浏览器。

body {
   margin: 20px;
}

.text {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-line-clamp: 2; /* number of lines to show */
   -webkit-box-orient: vertical;
}
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat tellus nulla eu dolor. Nulla porta bibendum lectus quis euismod. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat.
</div>

Unless you care about IE users, there is no need to do line-heightand max-heightfallbacks.

除非你关心 IE 用户,否则没有必要做line-heightmax-height回退。

回答by Erik Aigner

What you can do is the following:

您可以执行以下操作:

.max-lines {
  display: block;/* or inline-block */
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em;
  line-height: 1.8em;
}
<p class="max-lines">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vitae leo dapibus, accumsan lorem eleifend, pharetra quam. Quisque vestibulum commodo justo, eleifend mollis enim blandit eu. Aenean hendrerit nisl et elit maximus finibus. Suspendisse scelerisque consectetur nisl mollis scelerisque.</p>

where max-height:= line-height:× <number-of-lines>in em.

其中max-height:= line-height:× <number-of-lines>in em

回答by asimovwasright

Working Cross-browser Solution

工作跨浏览器解决方案

This problem has been plaguing us all for years.

这个问题多年来一直困扰着我们所有人。

To help in all cases, I have laid out the CSS only approach, and a jQuery approach in case the css caveats are a problem.

为了在所有情况下提供帮助,我已经列出了仅使用 CSS 的方法,以及一个 jQuery 方法,以防 css 警告出现问题。

Here's a CSS onlysolution I came up with that works in all circumstances, with a few minor caveats.

这是我想出的适用于所有情况的CSS解决方案,但有一些小问题。

The basics are simple, it hides the overflow of the span, and sets the max height based on the line height as suggested by Eugene Xa.

基础很简单,它隐藏了跨度的溢出,并根据 Eugene Xa 的建议设置了基于行高的最大高度。

Then there is a pseudo class after the containing div that places the ellipsis nicely.

然后在包含 div 之后有一个伪类,可以很好地放置省略号。

Caveats

注意事项

This solution will always place the ellipsis, regardless if there is need for it.

此解决方案将始终放置省略号,无论是否需要它。

If the last line ends with an ending sentence, you will end up with four dots....

如果最后一行以结束句结尾,您将得到四个点....

You will need to be happy with justified text alignment.

您需要对合理的文本对齐感到满意。

The ellipsis will be to the right of the text, which can look sloppy.

省略号将位于文本的右侧,这可能看起来很草率。

Code + Snippet

代码 + 片段

jsfiddle

提琴手

.text {
  position: relative;
  font-size: 14px;
  color: black;
  width: 250px; /* Could be anything you like. */
}

.text-concat {
  position: relative;
  display: inline-block;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */
  line-height: 1.2em;
  text-align:justify;
}

.text.ellipsis::after {
  content: "...";
  position: absolute;
  right: -12px; 
  bottom: 4px;
}

/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
<div class="text ellipsis">
  <span class="text-concat">
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in.

Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri.
  </span>
</div>

jQuery Approach

jQuery 方法

In my opinion this is the best solution, but not everyone can use JS. Basically, the jQuery will check any .text element, and if there are more chars than the preset max var, it will cut the rest off and add an ellipsis.

在我看来这是最好的解决方案,但并不是每个人都可以使用 JS。基本上,jQuery 将检查任何 .text 元素,如果字符数超过预设的 max var,它将切断其余部分并添加省略号。

There are no caveats to this approach, however this code example is meant only to demonstrate the basic idea - I wouldn't use this in production without improving on it for a two reasons:

这种方法没有任何警告,但是此代码示例仅用于演示基本思想 - 我不会在生产中使用它而不对其进行改进,原因有两个:

1) It will rewrite the inner html of .text elems. whether needed or not. 2) It does no test to check that the inner html has no nested elems - so you are relying a lot on the author to use the .text correctly.

1)它将重写.text elems的内部html。无论是否需要。2) 它没有检查内部 html 是否没有嵌套的 elems - 所以你非常依赖作者正确使用 .text 。

Edited

已编辑

Thanks for the catch @markzzz

感谢您的捕获@markzzz

Code & Snippet

代码和片段

jsfiddle

提琴手

setTimeout(function()
{
 var max = 200;
  var tot, str;
  $('.text').each(function() {
   str = String($(this).html());
   tot = str.length;
    str = (tot <= max)
     ? str
      : str.substring(0,(max + 1))+"...";
    $(this).html(str);
  });
},500); // Delayed for example only.
.text {
  position: relative;
  font-size: 14px;
  color: black;
  font-family: sans-serif;
  width: 250px; /* Could be anything you like. */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="text">
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young.
</p>

<p class="text">
Old men tend to forget what thought was like in their youth;
</p>
 <!-- Working Cross-browser Solution

This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->

回答by Pekka

As far as I can see, this would be possible only using height: (some em value); overflow: hiddenand even then it wouldn't have the fancy ...at the end.

据我所知,这只能使用height: (some em value); overflow: hidden,即使这样它最终也不会有幻想...

If that is not an option, I think it's impossible without some server side pre-processing (difficult because text flow is impossible to predict reliably) or jQuery (possible but probably complicated).

如果这不是一个选项,我认为如果没有一些服务器端预处理(很难,因为无法可靠地预测文本流)或 jQuery(可能但可能很复杂),这是不可能的。

回答by Martin Andersson

The solution from this threadis to use the jquery plugin dotdotdot. Not a CSS solution, but it gives you a lot of options for "read more" links, dynamic resizing etc.

线程的解决方案是使用 jquery 插件dotdotdot。不是 CSS 解决方案,但它为您提供了许多“阅读更多”链接、动态调整大小等选项。

回答by Mohammad Salman

following CSS class helped me in getting two line ellipsis.

以下 CSS 课程帮助我获得了两行省略号。

  .two-line-ellipsis {
        padding-left:2vw;
        text-overflow: ellipsis;
        overflow: hidden;
        width: 325px;
        line-height: 25px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        padding-top: 15px;
    }

回答by dreamer_

Currently you can't, but in future you will be able to use text-overflow:ellipis-lastline. Currently it's available with vendor prefix in Opera 10.60+: example

目前您不能,但将来您将能够使用text-overflow:ellipis-lastline. 目前它在 Opera 10.60+ 中可以使用供应商前缀:示例

回答by Miriam Salzer

I have a solution which works well but instead an ellipsis it uses a gradient. It works when you have dynamic text so you don't know if it will be long enough to need an ellipse. The advantages are that you don't have to do any JavaScript calculations and it works for variable width containers including table cells and is cross-browser. It uses a couple of extra divs, but it's very easy to implement.

我有一个运行良好的解决方案,但它使用渐变代替省略号。当您有动态文本时它会起作用,因此您不知道它是否足够长以需要椭圆。优点是您不必进行任何 JavaScript 计算,它适用于包括表格单元格在内的可变宽度容器,并且是跨浏览器的。它使用了几个额外的 div,但它很容易实现。

Markup:

标记:

<td>
    <div class="fade-container" title="content goes here">
         content goes here
         <div class="fade">
    </div>
</td>

CSS:

CSS:

.fade-container { /*two lines*/
    overflow: hidden;
    position: relative;
    line-height: 18px; 
    /* height must be a multiple of line-height for how many rows you want to show (height = line-height x rows) */
    height: 36px;
    -ms-hyphens: auto;
    -webkit-hyphens: auto;
    hyphens: auto;
    word-wrap: break-word;
}

.fade {
        position: absolute;
        top: 50%;/* only cover the last line. If this wrapped to 3 lines it would be 33% or the height of one line */
        right: 0;
        bottom: 0;
        width: 26px;
        background: linear-gradient(to right,  rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
}

blog post: http://salzerdesign.com/blog/?p=453

博文:http: //salzerdesign.com/blog/?p=453

example page: http://salzerdesign.com/test/fade.html

示例页面:http: //salzerdesign.com/test/fade.html

回答by Ali

.class{
   word-break: break-word;
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   line-height: 16px; /* fallback */
   max-height: 32px; /* fallback */
   -webkit-line-clamp: 2; /* number of lines to show */
   -webkit-box-orient: vertical;
}

回答by Nisharg Shah

If you want to focus on each letteryou can do like that, I refer to thisquestion

如果你想专注于letter你可以做的每一个,我参考这个问题

function truncate(source, size) {
  return source.length > size ? source.slice(0, size - 1) + "…" : source;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);

If you want to focus on each wordyou can do like that + space

如果你想专注于每个word你可以这样做+空间

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT 
    const newTitle = [];
    if (title.length > limit) {
        title.split(' ').reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join(' ') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);

If you want to focus on each wordyou can do like that + without space

如果你想专注于每个word你可以这样做+没有空间

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT 
    const newTitle = [];
    if (title.length > limit) {
        Array.prototype.slice.call(title).reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join('') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);