768

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

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

原文:

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

想要的输出(2行):

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

4

14 回答 14

1149

有一种方法可以使用非官方的 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 */
           line-clamp: 2; 
   -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>

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

于 2012-12-18T01:28:47.233 回答
164

您可以执行以下操作:

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

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

于 2013-03-02T14:51:01.080 回答
46

工作跨浏览器解决方案

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

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

这是我想出的一个唯一的 CSS解决方案,它适用于所有情况,但有一些小警告。

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

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

注意事项

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

如果最后一行以一个结尾句结束,那么你会以四个点结尾......

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

省略号将在文本的右侧,看起来很草率。

代码+片段

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 方法

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

这种方法没有任何警告,但是这个代码示例只是为了展示基本思想——我不会在生产中使用它而不改进它,原因有两个:

1) 它将重写 .text 元素的内部 html。不管需要与否。2) 没有测试检查内部 html 是否没有嵌套的元素 - 所以你非常依赖作者来正确使用 .text。

已编辑

感谢您的捕获@markzzz

代码和片段

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

于 2016-11-17T18:57:08.617 回答
34

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

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

于 2010-10-13T10:35:19.487 回答
20

以下 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;
    }
于 2017-05-19T07:00:49.193 回答
15

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

于 2013-07-31T08:38:02.223 回答
9

这对我有用:

div {
  width: 200px;
}

p {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  height: 2.6em; /* Fallback for non-webkit, line-height * 2 */
  line-height: 1.3em;
  -webkit-line-clamp: 2; /* if you change this, make sure to change the fallback line-height and height */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
  </p>
<div>

于 2021-04-13T02:46:40.090 回答
7
.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;
}
于 2019-09-30T20:10:15.320 回答
5

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

标记:

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

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%);
}

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

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

于 2013-05-22T21:21:50.747 回答
5

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

于 2011-01-18T02:30:27.830 回答
0

我真的很喜欢 line-clamp,但还不支持 firefox.. 所以我使用数学计算并隐藏溢出

.body-content.body-overflow-hidden h5 {
    max-height: 62px;/* font-size * line-height * lines-to-show(4 in this case) 63px if you go with jquery */
    overflow: hidden;
}
.body-content h5 {
    font-size: 14px; /* need to know this*/
    line-height:1,1; /*and this*/
}

现在假设您想通过带有链接的jQuery删除和添加此类,您将需要一个额外的像素,因此最大高度将为63 px,这是因为您每次都需要检查高度是否大于62px,但在 4 行的情况下,你会得到一个假真,所以一个额外的像素会解决这个问题,它不会产生任何额外的问题

我将为此粘贴一个咖啡脚本作为示例,使用几个默认隐藏的链接,类为 read-more 和 read-less,它将删除不需要溢出的链接并删除正文-溢出类

jQuery ->

    $('.read-more').each ->
        if $(this).parent().find("h5").height() < 63
             $(this).parent().removeClass("body-overflow-hidden").find(".read-less").remove()
             $(this).remove()
        else
            $(this).show()

    $('.read-more').click (event) ->
        event.preventDefault()
        $(this).parent().removeClass("body-overflow-hidden")
        $(this).hide()
        $(this).parent().find('.read-less').show()

    $('.read-less').click (event) ->
        event.preventDefault()
        $(this).parent().addClass("body-overflow-hidden")
        $(this).hide()
        $(this).parent().find('.read-more').show()
于 2015-04-21T14:11:55.430 回答
0

如果你想专注于每一个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);

如果你想专注于每个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);

如果你想专注于每一个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);

于 2019-05-31T16:56:44.367 回答
-3

基本示例代码,学习编码很容易。检查样式 CSS 注释。

table tr {
  display: flex;
}
table tr td {
  /* start */
  display: inline-block; /* <- Prevent <tr> in a display css */
  text-overflow: ellipsis;
  white-space: nowrap;
  /* end */
  padding: 10px;
  width: 150px; /* Space size limit */
  border: 1px solid black;
  overflow: hidden;
}
<table>
  <tbody>
    <tr>
      <td>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla egestas erat ut luctus posuere. Praesent et commodo eros. Vestibulum eu nisl vel dui ultrices ultricies vel in tellus.
      </td>
      <td>
        Praesent vitae tempus nulla. Donec vel porta velit. Fusce mattis enim ex. Mauris eu malesuada ante. Aenean id aliquet leo, nec ultricies tortor. Curabitur non mollis elit. Morbi euismod ante sit amet iaculis pharetra. Mauris id ultricies urna. Cras ut
        nisi dolor. Curabitur tellus erat, condimentum ac enim non, varius tempor nisi. Donec dapibus justo odio, sed consequat eros feugiat feugiat.
      </td>
      <td>
        Pellentesque mattis consequat ipsum sed sagittis. Pellentesque consectetur vestibulum odio, aliquet auctor ex elementum sed. Suspendisse porta massa nisl, quis molestie libero auctor varius. Ut erat nibh, fringilla sed ligula ut, iaculis interdum sapien.
        Ut dictum massa mi, sit amet interdum mi bibendum nec.
      </td>
    </tr>
    <tr>
      <td>
        Sed viverra massa laoreet urna dictum, et fringilla dui molestie. Duis porta, ligula ut venenatis pretium, sapien tellus blandit felis, non lobortis orci erat sed justo. Vivamus hendrerit, quam at iaculis vehicula, nibh nisi fermentum augue, at sagittis
        nibh dui et erat.
      </td>
      <td>
        Nullam mollis nulla justo, nec tincidunt urna suscipit non. Donec malesuada dolor non dolor interdum, id ultrices neque egestas. Integer ac ante sed magna gravida dapibus sit amet eu diam. Etiam dignissim est sit amet libero dapibus, in consequat est
        aliquet.
      </td>
      <td>
        Vestibulum mollis, dui eu eleifend tincidunt, erat eros tempor nibh, non finibus quam ante nec felis. Fusce egestas, orci in volutpat imperdiet, risus velit convallis sapien, sodales lobortis risus lectus id leo. Nunc vel diam vel nunc congue finibus.
        Vestibulum turpis tortor, pharetra sed ipsum eu, tincidunt imperdiet lorem. Donec rutrum purus at tincidunt sagittis. Quisque nec hendrerit justo.
      </td>
    </tr>
  </tbody>
</table>

于 2016-09-16T13:54:32.673 回答
-11

我一直在寻找这个,但后来我意识到,该死的我的网站使用 php!为什么不在文本输入上使用修剪功能并使用最大长度....

对于那些使用 php 的人来说,这也是一个可能的解决方案:http: //ideone.com/PsTaI

<?php
$s = "In the beginning there was a tree.";
$max_length = 10;

if (strlen($s) > $max_length)
{
   $offset = ($max_length - 3) - strlen($s);
   $s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}

echo $s;
?>
于 2013-06-03T00:58:22.620 回答