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

Pet*_*ter 448 css text overflow ellipsis

是否可以使用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 ...

Evg*_*eny 529

有一种方法,但它只是webkit.但是,当你将它与它结合使用line-height: X;max-height: X*N;,它也可以在其他浏览器中使用,只是没有省略号.

.giveMeEllipsis {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: N; /* number of lines to show */
   line-height: X;        /* fallback */
   max-height: X*N;       /* fallback */
}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/csYjC/1131/

  • 例如,使用某些字体大小到行高,您可以使用text-align:justify查看下一行的一部分,省略号不在最后一行的末尾,但重叠文本在该位置,它如果文本是左对齐的话会 (3认同)
  • 这是小提琴:http://jsfiddle.net/csYjC/1122/当我准备它时,我发现,最后一行的那一部分只有在有填充时才可见 (3认同)
  • 如果您在使用-webkit-box-orient:vertical;时遇到问题,请在编译scss时尝试使用此`/ *自动前缀:忽略下一个* / -webkit-box-orient:Vertical;`。 (3认同)
  • 请注意,在此注释中,-webkit-line-clamp不尊重可见性:隐藏.这花了我几个小时的调试.这是一个支持错误报告:https://bugs.webkit.org/show_bug.cgi?id = 45399. (2认同)

Eri*_*ner 95

你能做的是以下几点:

.max-lines {
  display: block; /* or inline-block */
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em;
  line-height: 1.8em;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 像文本溢出一样工作:剪辑,因为它没有显示(...) (8认同)
  • 我相信你必须添加属性 `display: -webkit-box; -webkit线夹:2;-webkit-box-orient: Vertical;` 使省略号出现。但这仅适用于 Chrome。对于也适用于 Firefox 的解决方案,请查看此处:/sf/answers/1441655141/ 这是关于该主题的有用教程:https://css-tricks.com/line-clampin/ (7认同)
  • 或者在Chrome 34中. (5认同)
  • 在Firefox 28中不起作用.可悲的是. (4认同)

asi*_*ght 33

使用跨浏览器解决方案

多年来这个问题困扰着我们所有人......

为了在所有情况下提供帮助,我已经列出了仅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. */
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

jQuery方法

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

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

1)它将重写.text elems的内部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.
Run Code Online (Sandbox Code Playgroud)
.text {
  position: relative;
  font-size: 14px;
  color: black;
  font-family: sans-serif;
  width: 250px; /* Could be anything you like. */
}
Run Code Online (Sandbox Code Playgroud)
<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 -->
Run Code Online (Sandbox Code Playgroud)

  • 您的CSS解决方案不是很好,因为文本不溢出的情况如何?它也显示“ ...” ... (2认同)

Pek*_*ica 30

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

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

  • 这似乎适用于任何font-size .mytext {overflow:hidden; line-height:1.2em; 最大高度:2.4em; } (15认同)

Mar*_*son 15

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


Oli*_*ape 14

2024 年更新:更短的方法

这是根据Tailwind CSS 3.4+,您可以使用该实用程序line-clamp-*,但下面是 css 版本。

div {
  width: 200px;
}

p {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
  </p>
<div>
Run Code Online (Sandbox Code Playgroud)

具有后备功能的浏览器安全方法:

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;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
  </p>
<div>
Run Code Online (Sandbox Code Playgroud)


小智 13

对于 React 用户,使用内联样式:

<p
    style={{
        overflow: "hidden",
        textOverflow: "ellipsis",
        display: "-webkit-box",
        lineClamp: 2,
        WebkitLineClamp: 2,
        WebkitBoxOrient: "vertical",
    }}
>
    Some Text
</p>;
Run Code Online (Sandbox Code Playgroud)


小智 9

以下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;
    }
Run Code Online (Sandbox Code Playgroud)


Ali*_*Ali 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;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

  • 这对多行字符串不起作用,因为它还需要设置white-scace:nowrap.见[here](http://www.quirksmode.org/css/textoverflow.html). (5认同)
  • 这不是CSS3规范的一部分:http://dev.w3.org/csswg/css3-ui/#text-overflow (5认同)

Mir*_*zer 5

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

标记:

<td>
    <div class="fade-container" title="content goes here">
         content goes here
         <div class="fade">
    </div>
</td>
Run Code Online (Sandbox Code Playgroud)

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%);
}
Run Code Online (Sandbox Code Playgroud)

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

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