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

发布于 2025-01-18 01:21:47 字数 568 浏览 4 评论 0 原文

是否可以使用 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
千万不要! Dapibus sed aenean、magna sagittis、lorem velit

想要的输出(2 行):

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

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

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

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

wanted output (2 lines):

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

っ〆星空下的拥抱 2025-01-25 01:21:47

有一种方法可以使用非正式 line-clamp 语法,从Firefox 68开始在所有主要浏览器中。

body {
   margin: 20px;
}

.text {
   overflow: hidden;
   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-Height max-height sholdbacks。

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

body {
   margin: 20px;
}

.text {
   overflow: hidden;
   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>

Unless you care about IE users, there is no need to do line-height and max-height fallbacks.

孤寂小茶 2025-01-25 01:21:47

您可以执行以下操作:

.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: × in em

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.

忆梦 2025-01-25 01:21:47

工作跨浏览器解决方案

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

为了在所有情况下,我都列出了CSS方法,并且如果CSS警告是一个问题,则采用jQuery方法。

这是我在所有情况下都提出的 CSS 解决方案,有一些小警告。

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

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

警告

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

如果最后一行以结尾句子结尾,您将最终有四个点....

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

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

代码 + smippet

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 Elems的内部HTML 。是否需要。
2)检查内部HTML是否没有嵌套的Elems,因此您非常依赖作者正确使用.TEXT。

编辑

感谢您的收获@markzzz

代码&amp; smippet

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

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.

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

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.

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

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

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.

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.

Edited

Thanks for the catch @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 -->

心意如水 2025-01-25 01:21:47

以下CSS类将文本限制为两行,并插入一个省略号以指示溢出的文本。

.two-line-ellipsis {
  overflow: hidden;
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
<div class="two-line-ellipsis">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in ex sit amet diam efficitur pellentesque. Mauris posuere scelerisque libero, nec pretium mauris molestie non. Nulla aliquam sollicitudin egestas. Fusce aliquet elit vitae mi volutpat vehicula.
  Vestibulum vel sapien enim. Nulla eu volutpat ex, ac faucibus urna. Etiam mattis rutrum ullamcorper. Ut sagittis, erat sit amet vulputate commodo, nisl lacus aliquet magna, vel condimentum ante felis rutrum nibh. Suspendisse ut lorem rutrum, molestie
  velit eget, hendrerit lorem. Vivamus rutrum nunc elit, nec lacinia risus viverra ut.</div>

The following CSS class restricts text to two lines, and inserts an ellipsis to indicate overflowing text.

.two-line-ellipsis {
  overflow: hidden;
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
<div class="two-line-ellipsis">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in ex sit amet diam efficitur pellentesque. Mauris posuere scelerisque libero, nec pretium mauris molestie non. Nulla aliquam sollicitudin egestas. Fusce aliquet elit vitae mi volutpat vehicula.
  Vestibulum vel sapien enim. Nulla eu volutpat ex, ac faucibus urna. Etiam mattis rutrum ullamcorper. Ut sagittis, erat sit amet vulputate commodo, nisl lacus aliquet magna, vel condimentum ante felis rutrum nibh. Suspendisse ut lorem rutrum, molestie
  velit eget, hendrerit lorem. Vivamus rutrum nunc elit, nec lacinia risus viverra ut.</div>

聊慰 2025-01-25 01:21:47

据我所知,这只能使用 height: (some em value); Overflow:hidden 即使这样,它的末尾也不会有花哨的 ...

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

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

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

天赋异禀 2025-01-25 01:21:47

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

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

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>

2024 UPDATE: Shorter Approach

This is according to Tailwind CSS 3.4+ wherein you can use the utility line-clamp-* but below is the css version.

div {
  width: 200px;
}

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

Browser-safe approach with fallbacks:

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>

你怎么这么可爱啊 2025-01-25 01:21:47

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

The solution from this thread is 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.

暮年 2025-01-25 01:21:47

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

<p
    style={{
        overflow: "hidden",
        textOverflow: "ellipsis",
        display: "-webkit-box",
        lineClamp: 2,
        WebkitLineClamp: 2,
        WebkitBoxOrient: "vertical",
    }}
>
    Some Text
</p>;

For React users, with inline styles:

<p
    style={{
        overflow: "hidden",
        textOverflow: "ellipsis",
        display: "-webkit-box",
        lineClamp: 2,
        WebkitLineClamp: 2,
        WebkitBoxOrient: "vertical",
    }}
>
    Some Text
</p>;
木森分化 2025-01-25 01:21:47
.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;
}
.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;
}
不羁少年 2025-01-25 01:21:47

目前您还不能,但将来您将能够使用 text-overflow:ellipis-lastline。目前它的供应商前缀为
Opera 10.60+:示例

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

冰葑 2025-01-25 01:21:47

我有一个效果很好的解决方案,但它使用渐变代替省略号。当您有动态文本时,它会起作用,因此您不知道它是否足够长而需要椭圆形。优点是您不必执行任何 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

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.

Markup:

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

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

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

桃酥萝莉 2025-01-25 01:21:47

截至(几乎)2023 年,不再需要一些旧的 CSS 规则。

这些显示了所需的最低,以及工作交叉浏览器 尽管有前缀语法:

.line-clamp {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}

.line-clamp-2 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.line-clamp-3 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

As of (almost) 2023, some older css rules are no longer needed.

These show the minimum required, and work cross browser despite the prefixed syntax:

.line-clamp {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}

.line-clamp-2 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.line-clamp-3 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

陪你到最终 2025-01-25 01:21:47

在这种情况下,下一个解决方案在我需要缩短长电子邮件的时间段内对我有用:

.ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  overflow-wrap: normal;
}

There was a case in which this next solution worked for me in a span where I needed to cut long emails short:

.ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  overflow-wrap: normal;
}
2025-01-25 01:21:47

如果您遇到了水平文本剪辑问题,则可能与溢出的使用有关:隐藏 line-height-Height 结合使用。尝试在下面使用此最小值解决方案,该解决方案使用 carc 的CSS变量对其进行稍微隔绝。

注意:这不是垂直响应的。意思是,它具有设定的高度,如果文本内容小于 - lines ,则容器将不相应地收缩。

--lines: 7;
--line-height: 1.5;

overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;

-webkit-line-clamp: var(--lines);
line-height: var(--line-height);

min-height: calc(var(--line-height) * (1em * var(--lines))); 

If you are running into horizontal text clipping issues, it probably has to do with the use of overflow: hidden combined with line-height. Try using this min-height solution below, that uses CSS variables with calc to dummy-proof it a little.

NOTE: This is not vertically responsive. Meaning, that it has a set height, and if the text content is less than the --lines, the container will not shrink accordingly.

--lines: 7;
--line-height: 1.5;

overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;

-webkit-line-clamp: var(--lines);
line-height: var(--line-height);

min-height: calc(var(--line-height) * (1em * var(--lines))); 
温馨耳语 2025-01-25 01:21:47

我真的很喜欢线夹,但还没有支持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*/
}

现在可以说您要删除并通过链接添加此类,您需要有一个额外的像素,因此最大高度将是63 px,这是因为您需要每次检查高度的灰色,而高度是否超过62px,但是在4行的情况下,您会得到一个错误的true,所以额外的像素会解决此问题而且它不会造成任何额外的问题,

我会为此而粘贴咖啡本,只是为了一个例子,使用默认情况下隐藏的几个链接,而类别读取和无读,它将删除溢出的链接不需要它并删除车身跨流类

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

I really like line-clamp, but no support for firefox yet.. so i go with a math calc and just hide the overflow

.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*/
}

now lets say you want to remove and add this class via jQuery with a link, you will need to have an extra pixel so the max-height it will be 63 px, this is because you need to check every time if the height greather than 62px, but in the case of 4 lines you will get a false true, so an extra pixel will fix this and it will no create any extra problems

i will paste a coffeescript for this just to be an example, uses a couple of links that are hidden by default, with classes read-more and read-less, it will remove the ones that the overflow is not need it and remove the body-overflow classes

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()
噩梦成真你也成魔 2025-01-25 01:21:47

如果要专注于每个字母可以这样做,我参考 this

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 您可以这样做 + Space

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

If you want to focus on each letter you can do like that, I refer to this question

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 word you can do like that + space

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 word you can do like that + without space

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

寄居者 2025-01-25 01:21:47

line-clamp属性限制了段落中的行数,并在末尾添加了一个省略(…)。
整个示例:
我在这里有一个答案

The line-clamp property limits the number of lines in the paragraph and adds an ellipsis(…) at the end.
The whole example: Github

I've got an answer here medium
enter image description here

沫尐诺 2025-01-25 01:21:47
.word-limit{
   display: block;
   text-overflow: ellipsis;
   white-space: nowrap;
   word-wrap: break-word;
   overflow: hidden;
}
.word-limit{
   display: block;
   text-overflow: ellipsis;
   white-space: nowrap;
   word-wrap: break-word;
   overflow: hidden;
}
岁吢 2025-01-25 01:21:47
.text-container {
    display: -webkit-box;
    -webkit-line-clamp: 2; /* Number of lines to show */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    /* Additional styles for the container (e.g., height, width, etc.) */
    height: 3em; /* Set the height to accommodate two lines of text */
    width: 300px; /* Set the width as needed */
}
.text-container {
    display: -webkit-box;
    -webkit-line-clamp: 2; /* Number of lines to show */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    /* Additional styles for the container (e.g., height, width, etc.) */
    height: 3em; /* Set the height to accommodate two lines of text */
    width: 300px; /* Set the width as needed */
}
廻憶裏菂餘溫 2025-01-25 01:21:47

基本示例代码,学习代码很容易。检查样式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>

Basic Example Code, learning to code is easy. Check Style CSS comments.

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>

黯然 2025-01-25 01:21:47

我一直在寻找这个,但后来我意识到,该死的我的网站使用 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;
?>

I've been looking around for this, but then I realize, damn my website uses php!!!
Why not use the trim function on the text input and play with the max length....

Here is a possible solution too for those using 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;
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文