天天看點

使用CSS将文字長度限制為n行

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

text-overflow: ellipsis;

僅适用于1行文字。

原文:

納圖克足癬,阿裡卡姆,克拉斯

Tincidunt elit purus lectus,vel utquet,elementum nunc

nunc rhoncus placerat urna! 坐吧! 烏頭企鵝

mus tincidunt! Dapibus sed aenean,magna sagittis,lorem velit

所需的輸出(2行):

納圖克足癬,阿裡卡姆,克拉斯

Tincidunt elit purus lectus,vel utquet,elementum ...

#1樓

有一種方法,但是它僅适用于webkit。 但是,将其與

line-height: X;

結合使用時

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

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

#2樓

您可以執行以下操作:

.max-lines {
  display: block; /* or inline-block */
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em;
  line-height: 1.8em;
}
           

其中

max-height:

=

line-height:

×

em

<number-of-lines>

#3樓

我有一個效果很好的解決方案,但省略号使用漸變。 當您具有動态文本時,它可以工作,是以您不知道它是否足夠長,需要橢圓形。 優點是您不必執行任何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

#4樓

我一直在尋找這個,但後來我意識到,該死的我的網站使用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;
?>
           

#5樓

該線程的解決方案是使用jquery插件dotdotdot 。 不是CSS解決方案,但是它為您提供了更多“讀取更多”連結,動态調整大小等選項。

#6樓

我真的很喜歡線夾,但是還不支援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删除并添加帶有連結的此類,則需要有一個額外的像素,是以max-height為63 px,這是因為您需要每次檢查高度是否大于62像素,但是在4行的情況下,您将得到一個假的true,是以一個額外的像素将解決此問題,并且不會造成任何額外的問題

我将為此粘貼一個咖啡腳本,僅作為示例,使用預設情況下隐藏的幾個連結,這些類具有“ 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()
           

#7樓

據我所知,這隻能使用

height: (some em value); overflow: hidden

height: (some em value); overflow: hidden

,即使那樣也沒有幻想

...

最後。

如果這不是一個選擇,我認為沒有伺服器端的預處理(很難,因為文本流無法可靠地預測)或jQuery(可能,但可能很複雜)是不可能的。

#8樓

基本示例代碼,學習代碼很容易。 檢查樣式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>                

#9樓

跨浏覽器的有效解決方案

多年來,這個問題困擾着我們所有人。

為了在所有情況下都提供幫助,我提出了僅CSS的方法,以及在css警告有問題的情況下使用jQuery的方法。

這是我想出的僅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元素,如果字元數超過預設的max 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 -->                

#10樓

以下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;
    }
           

#11樓

目前

text-overflow:ellipis-lastline

無法使用,但将來您将可以使用

text-overflow:ellipis-lastline

。 目前,它在Opera 10.60+中可用,帶有供應商字首: example

#12樓

如果您想專注于每個

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

#13樓

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