Con CSS, use " ... " para el bloque desbordado de varias líneas


Con

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

"..."se mostrará al final de la línea si se desbordó. Sin embargo, esto solo se mostrará en una línea. Pero me gustaría que se mostrara en varias líneas.

Puede parecer:

+--------------------+
|abcde feg hij   dkjd|
|dsji jdia js ajid  s|
|jdis ajid dheu d ...|/*Here it's overflowed, so "..." is shown. */
+--------------------+
Author: Sjoerd, 2011-06-03

17 answers

También hay varios complementos de jquery que se ocupan de este problema, pero muchos no manejan varias líneas de texto. Las siguientes obras:

También hay algunas pruebas de preformance .

 83
Author: Jim Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-08 09:15:52

He hackeado alrededor hasta que he logrado lograr algo cercano a esto. Viene con algunas advertencias:

  1. No es CSS puro; tienes que añadir algunos elementos HTML. Sin embargo, no se requiere JavaScript.
  2. Los puntos suspensivos están alineados a la derecha en la última línea. Esto significa que si su texto no está alineado a la derecha o justificado, puede haber un espacio notorio entre la última palabra visible y los puntos suspensivos (dependiendo de la longitud de la primera palabra oculta).
  3. El espacio para los puntos suspensivos siempre están reservados. Esto significa que si el texto encaja en la caja casi con precisión, puede ser innecesariamente truncado (la última palabra está oculta, aunque técnicamente no tendría que hacerlo).
  4. Su texto debe tener un color de fondo fijo, ya que estamos usando rectángulos de color para ocultar los puntos suspensivos en los casos en que no es necesario.

También debo señalar que el texto se romperá en un límite de palabra, no en un límite de caracteres. Esto fue deliberado (ya que considero eso es mejor para textos más largos), pero debido a que es diferente de lo que text-overflow: ellipsis hace, pensé que debería mencionarlo.

Si puedes vivir con estas advertencias, el HTML se ve así:

<div class="ellipsify">
    <div class="pre-dots"></div>
    <div class="dots">&hellip;</div>
    <!-- your text here -->
    <span class="hidedots1"></span>
    <div class="hidedots2"></div>
</div>

Y este es el CSS correspondiente, usando el ejemplo de un cuadro de 150 píxeles de ancho con tres líneas de texto sobre un fondo blanco. Asume que tiene un reset de CSS o similar que establece márgenes y rellenos a cero cuando sea necesario.

/* the wrapper */
.ellipsify {
    font-size:12px;
    line-height:18px;
    height: 54px;       /* 3x line height */
    width: 150px;
    overflow: hidden;
    position: relative; /* so we're a positioning parent for the dot hiders */
    background: white;
}

/* Used to push down .dots. Can't use absolute positioning, since that
   would stop the floating. Can't use relative positioning, since that
   would cause floating in the wrong (namely: original) place. Can't 
   change height of #dots, since it would have the full width, and
   thus cause early wrapping on all lines. */
.pre-dots {
    float: right;
    height: 36px;  /* 2x line height (one less than visible lines) */
}

.dots {
    float: right; /* to make the text wrap around the dots */
    clear: right; /* to push us below (not next to) .pre-dots */
}

/* hides the dots if the text has *exactly* 3 lines */
.hidedots1 {
    background: white;
    width: 150px;
    height: 18px;       /* line height */
    position: absolute; /* otherwise, because of the width, it'll be wrapped */
}

/* hides the dots if the text has *less than* 3 lines */
.hidedots2 {
    background: white; 
    width: 150px;
    height: 54px;       /* 3x line height, to ensure hiding even if empty */
    position: absolute; /* ensures we're above the dots */
}

El resultado se ve como esto:

imagen del resultado renderizado con diferentes longitudes de texto

Para aclarar cómo funciona, aquí está la misma imagen, excepto que .hidedots1 está iluminado en rojo, y .hidedots2 en cian. Estos son los rectángulos que ocultan los puntos suspensivos cuando no hay texto invisible:

la misma imagen que la anterior, excepto que los elementos auxiliares se resaltan en color

Probado en IE9, IE8 (emulado), Chrome, Firefox, Safari y Opera. No funciona en IE7.

 58
Author: balpha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-06 18:44:07

Aquí hay un reciente css-tricks artículo que discute esto.

Algunas de las soluciones en el artículo anterior (que no se mencionan aquí) son

1) -webkit-line-clamp y 2) Coloque un elemento absolutamente posicionado en la parte inferior derecha con fade out

Ambos métodos asumen el siguiente marcado:

<div class="module"> /* Add line-clamp/fade class here*/
  <p>Text here</p>
</div>

Con css

.module {
  width: 250px;
  overflow: hidden;
}

1)-webkit-line-clamp

Línea-violín de la abrazadera (..para un máximo de 3 líneas)

.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;  
  max-height: 3.6em; /* I needed this to get it to work */
}

2) fundido fuera

Digamos que establece la altura de la línea a 1.2 em. Si queremos exponer tres líneas de texto, solo podemos hacer la altura del contenedor 3,6 em (1,2 em × 3). El desbordamiento oculto ocultará el resto.

Fade out FIDDLE

p
{
    margin:0;padding:0;
}
.module {
  width: 250px;
  overflow: hidden;
  border: 1px solid green;
  margin: 10px;
}

.fade {
  position: relative;
  height: 3.6em; /* exactly three lines */
}
.fade:after {
  content: "";
  text-align: right;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 70%;
  height: 1.2em;
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
}

Solución # 3-Una combinación usando @ soporta

Podemos usar @ supports para aplicar la abrazadera de línea de webkit en navegadores webkit y aplicar fade out en otros navegador.

@soporta abrazadera de línea con fade fallback fiddle

<div class="module line-clamp">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

CSS

.module {
  width: 250px;
  overflow: hidden;
  border: 1px solid green;
  margin: 10px;
}

.line-clamp {
      position: relative;
      height: 3.6em; /* exactly three lines */
    }
.line-clamp:after {
      content: "";
      text-align: right;
      position: absolute;
      bottom: 0;
      right: 0;
      width: 70%;
      height: 1.2em;
      background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
 }

@supports (-webkit-line-clamp: 3) {
    .line-clamp {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;  
        max-height:3.6em; /* I needed this to get it to work */
        height: auto;
    }
    .line-clamp:after {
        display: none;
    }
}
 39
Author: Danield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-18 07:57:50

El siguiente enlace proporciona una solución HTML / CSS pura para este problema.

Soporte del navegador-como se indica en el artículo:

Hasta ahora hemos probado en Safari 5.0, es decir, 9 (debe estar en modo estándar), Opera 12 y Firefox 15.

Los navegadores más antiguos seguirán funcionando bastante bien, ya que la carne del diseño está en posición normal, margen y propiedades de relleno. si su plataforma es más antigua (por ejemplo, Firefox 3.6, IE 8), puede utilizar el método, pero rehacer el gradiente como un imagen PNG independiente o filtro DirectX.

Http://www.mobify.com/dev/multiline-ellipsis-in-pure-css

El css:

p { margin: 0; padding: 0; font-family: sans-serif;}

.ellipsis {
    overflow: hidden;
    height: 200px;
    line-height: 25px;
    margin: 20px;
    border: 5px solid #AAA; }

.ellipsis:before {
    content:"";
    float: left;
    width: 5px; height: 200px; }

.ellipsis > *:first-child {
    float: right;
    width: 100%;
    margin-left: -5px; }        

.ellipsis:after {
    content: "\02026";  

    box-sizing: content-box;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;

    float: right; position: relative;
    top: -25px; left: 100%; 
    width: 3em; margin-left: -3em;
    padding-right: 5px;

    text-align: right;

    background: -webkit-gradient(linear, left top, right top,
        from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
    background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);           
    background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }

El html:

<div class="ellipsis">
    <div>
        <p>Call me Ishmael.  Some years ago &ndash; never mind how long precisely &ndash; having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.  It is a way I have of driving off the spleen, and regulating the circulation.  Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off &ndash; then, I account it high time to get to sea as soon as I can.</p>  
    </div>
</div>

El violín

(cambiar el tamaño de la ventana del navegador para las pruebas)

 33
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-17 10:36:53

Después de revisar la especificación W3 para text-overflow, no creo que esto sea posible usando solo CSS. Elipsis es una propiedad new-ish, por lo que probablemente no ha recibido mucho uso o retroalimentación hasta ahora.

Sin embargo, este tipo parece haber hecho una pregunta similar (o idéntica), y alguien fue capaz de llegar a una buena solución jQuery. Puede hacer una demostración de la solución aquí: http://jsfiddle.net/MPkSF /

Si javascript no es una opción, creo que puede no habrá suerte...

 21
Author: Jeff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:33

Solo quiero agregar a esta pregunta para completar.

 10
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-20 15:00:01

Gran pregunta... Me gustaría que hubiera una respuesta, pero esto es lo más cercano que se puede conseguir con CSS en estos días. Sin puntos suspensivos, pero aún así bastante utilizable.

overflow: hidden;
line-height: 1.2em;
height: 3.6em;      // 3 lines * line-height
 7
Author: Adam Fraser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-19 19:58:06

He encontrado esta solución css (scss) que funciona bastante bien. En los navegadores webkit muestra los puntos suspensivos y en otros navegadores solo trunca el texto. Lo cual está bien para mi uso previsto.

$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;

h2 {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

Un ejemplo del creador: http://codepen.io/martinwolf/pen/qlFdp

 6
Author: Nikola Lajic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-09 10:45:09

Aquí está la solución más cercana que podría obtener usando solo css.

HTML

<div class="ellipsis"> <span>...</span>
Hello this is Mr_Green from Stackoverflow. I love CSS. I live in CSS and I will never leave working on CSS even my work is on other technologies.</div>

CSS

div {
    height: 3em;
    line-height: 1.5em;
    width: 80%;
    border: 1px solid green;
    overflow: hidden;
    position: relative;
}
div:after {
    content:". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . .";
    background-color: white;
    color: white;
    display: inline;
    position: relative;
    box-shadow: 8px 1px 1px white;
    z-index: 1;
}
span {
    position: absolute;
    bottom: 0px;
    right: 0px;
    background-color: white;
}

Violín de Trabajo (cambiar el tamaño de la ventana para comprobar )

Enlace a mi blog para explicación

Fiddle actualizado

Espero que ahora algún experto en css tenga idea de cómo hacerlo perfecto. :)

 6
Author: Mr_Green,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 04:11:27

En su caso, lo siguiente será eficiente y suficiente.

  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
 6
Author: pxthxk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-01 20:05:47

Un poco tarde para esta fiesta, pero se me ocurrió, lo que creo, es una solución única. En lugar de intentar insertar sus propios puntos suspensivos a través de trucos css o js, pensé en intentar rodar con la restricción de una sola línea. Así que duplico el texto para cada "línea" y solo uso una sangría de texto negativa para asegurarme de que una línea comienza donde se detiene la última. VIOLÍN

CSS:

#wrapper{
    font-size: 20pt;
    line-height: 22pt;
    width: 100%;
    overflow: hidden;
    padding: 0;
    margin: 0;
}

.text-block-line{
    height: 22pt;
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    width: auto;
}
.text-block-line:last-child{
    text-overflow: ellipsis;
}

/*the follwing is suboptimal but neccesary I think. I'd probably just make a sass mixin that I can feed a max number of lines to and have them avialable. Number of lines will need to be controlled by server or client template which is no worse than doing a character count clip server side now. */
.line2{
    text-indent: -100%;
}
.line3{
    text-indent: -200%;
}
.line4{
    text-indent: -300%;
}

HTML:

<p id="wrapper" class="redraw">
    <span class="text-block-line line1">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
    <span class="text-block-line line2">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
    <span class="text-block-line line3">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
    <span class="text-block-line line4">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
</p>

Más detalles en el violín. Hay un problema con el reflujo del navegador para el que uso un redibujo JS y así lo compruebo, pero este es el concepto básico. Cualquier pensamiento/sugerencia son muy apreciados.

 4
Author: lupos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-04 21:13:18

Gracias @balpha y @Kevin, combino dos métodos juntos.

No se necesita js en este método.

Puede usar background-image y no necesita gradiente para ocultar puntos.

El innerHTML de .ellipsis-placeholder no es necesario, utilizo .ellipsis-placeholder para mantener la misma anchura y altura con .ellipsis-more. Podrías usar display: inline-block en su lugar.

.ellipsis {
    overflow: hidden;
    position: relative;
}
.ellipsis-more-top {/*push down .ellipsis-more*/
    content: "";
    float: left;
    width: 5px;
}
.ellipsis-text-container {
    float: right;
    width: 100%;
    margin-left: -5px;
}
.ellipsis-more-container {
    float: right;
    position: relative;
    left: 100%;
    width: 5px;
    margin-left: -5px;
    border-right: solid 5px transparent;
    white-space: nowrap;
}
.ellipsis-placeholder {/*keep text around ,keep it transparent ,keep same width and height as .ellipsis-more*/
    float: right;
    clear: right;
    color: transparent;
}
.ellipsis-placeholder-top {/*push down .ellipsis-placeholder*/
    float: right;
    width: 0;
}
.ellipsis-more {/*ellipsis things here*/
    float: right;
}
.ellipsis-height {/*the total height*/
    height: 3.6em;
}
.ellipsis-line-height {/*the line-height*/
    line-height: 1.2;
}
.ellipsis-margin-top {/*one line height*/
    margin-top: -1.2em;
}
.ellipsis-text {
    word-break: break-all;
}
<div class="ellipsis ellipsis-height ellipsis-line-height">
    <div class="ellipsis-more-top ellipsis-height"></div>
    <div class="ellipsis-text-container">
        <div class="ellipsis-placeholder-top ellipsis-height ellipsis-margin-top"></div>
        <div class="ellipsis-placeholder">
           <span>...</span><span>more</span>
        </div>
        <span class="ellipsis-text">text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </span>
    </div>
    <div class="ellipsis-more-container ellipsis-margin-top">
        <div class="ellipsis-more">
            <span>...</span><span>more</span>
        </div>
    </div>
</div>

Jsfiddler

 3
Author: Defims,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-20 06:20:23

Hay muchas respuestas aquí, pero necesitaba una que fuera:

  • Solo CSS
  • A prueba de futuro (se vuelve más compatible con el tiempo)
  • No va a separar las palabras (solo se rompe en espacios)

La advertencia es que no proporciona puntos suspensivos para los navegadores que no admiten la regla -webkit-line-clamp (actualmente IE, Edge, Firefox), pero sí utiliza un degradado para desvanecer su texto.

.clampMe {
  position: relative;
  height: 2.4em; 
  overflow: hidden;
}

.clampMe:after {
  content: "";
  text-align: right;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 50%;
  height: 1.2em; /* Just use multiples of the line-height */
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 80%);
}

/* Now add in code for the browsers that support -webkit-line-clamp and overwrite the non-supportive stuff */
@supports (-webkit-line-clamp: 2) {
  .clampMe {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
  }
  
  .clampMe:after {
    display: none;
  }
}
<p class="clampMe">There's a lot more text in here than what you'll ever see. Pellentesque habitant testalotish morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

Puedes verlo en acción en esto CodePen y también puedes ver una versión de Javascript aquí (sin jQuery).

 3
Author: NilsyNils,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-23 15:18:31

La solución Javascript será mejor

  • obtener el número de líneas de texto
  • alternar is-ellipsis clase si el cambio de tamaño o elment de la ventana

GetRowRects

Element.getClientRects() funciona como this

introduzca la descripción de la imagen aquí

Cada rects en la misma fila tiene el mismo valor top, así que averigua los rects con diferente valor top, como this

introduzca la descripción de la imagen aquí

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

Float ...more

Como esto

introduzca la descripción de la imagen aquí

Detectar cambio de tamaño de ventana o elemento

Como esto

introduzca la descripción de la imagen aquí

introduzca la descripción de la imagen aquí

introduzca la descripción de la imagen aquí

 2
Author: Defims,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-08 08:15:13
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical; 

Ver más, haga clic aquí

 0
Author: elrrrrrrr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-10 02:47:51

Un método css puro base on-webkit-line-clamp:

@-webkit-keyframes ellipsis {/*for test*/
    0% { width: 622px }
    50% { width: 311px }
    100% { width: 622px }
}
.ellipsis {
    max-height: 40px;/* h*n */
    overflow: hidden;
    background: #eee;

    -webkit-animation: ellipsis ease 5s infinite;/*for test*/
    /**
    overflow: visible;
    /**/
}
.ellipsis .content {
    position: relative;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-pack: center;
    font-size: 50px;/* w */
    line-height: 20px;/* line-height h */
    color: transparent;
    -webkit-line-clamp: 2;/* max row number n */
    vertical-align: top;
}
.ellipsis .text {
    display: inline;
    vertical-align: top;
    font-size: 14px;
    color: #000;
}
.ellipsis .overlay {
    position: absolute;
    top: 0;
    left: 50%;
    width: 100%;
    height: 100%;
    overflow: hidden;

    /**
    overflow: visible;
    left: 0;
    background: rgba(0,0,0,.5);
    /**/
}
.ellipsis .overlay:before {
    content: "";
    display: block;
    float: left;
    width: 50%;
    height: 100%;

    /**
    background: lightgreen;
    /**/
}
.ellipsis .placeholder {
    float: left;
    width: 50%;
    height: 40px;/* h*n */

    /**
    background: lightblue;
    /**/
}
.ellipsis .more {
    position: relative;
    top: -20px;/* -h */
    left: -50px;/* -w */
    float: left;
    color: #000;
    width: 50px;/* width of the .more w */
    height: 20px;/* h */
    font-size: 14px;

    /**
    top: 0;
    left: 0;
    background: orange;
    /**/
}
<div class='ellipsis'>
    <div class='content'>
        <div class='text'>text text text text text text text text text text text text text text text text text text text text text </div>
        <div class='overlay'>
            <div class='placeholder'></div>
            <div class='more'>...more</div>
        </div>
    </div>
</div>
 0
Author: Defims,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-11 14:38:33

Encontré un truco de javascript, pero tienes que usar la longitud de la cadena. Digamos que desea 3 líneas de ancho 250px, puede calcular la longitud por línea, es decir,

//get the total character length.
//Haha this might vary if you have a text with lots of "i" vs "w"
var totalLength = (width / yourFontSize) * yourNumberOfLines

//then ellipsify
function shorten(text, totalLength) {
    var ret = text;
    if (ret.length > totalLength) {
        ret = ret.substr(0, totalLength-3) + "...";
    }
    return ret;
}
 -1
Author: Tremmillicious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-15 18:43:29