Envuelva un texto dentro de solo dos líneas dentro de div


85

Quiero envolver un texto dentro de solo dos líneas dentro de div de ancho específico. Si el texto va más allá de la longitud de dos líneas, quiero mostrar puntos suspensivos. ¿Hay alguna forma de hacerlo usando CSS?

p.ej

Sample text showing wrapping
of text in only two line...

Gracias

Respuestas:


142

Es posible limitar la salida a dos líneas de texto con CSS, si establece el line-heighty heightdel elemento, y establece overflow:hidden;:

#someDiv {
    line-height: 1.5em;
    height: 3em;       /* height is 2x line-height, so two lines will display */
    overflow: hidden;  /* prevents extra lines from being visible */
}

--- jsFiddle DEMO ---

Alternativamente, puede usar CSS text-overflowy white-spacepropiedades para agregar puntos suspensivos, pero esto solo parece funcionar para una sola línea.

#someDiv {
    line-height: 1.5em;
    height: 3em;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100%;
}

Y una demostración:

--- jsFiddle DEMO ---

Lograr múltiples líneas de texto y puntos suspensivos parece ser el ámbito de javascript.


11
Solo veo una línea
cruzada

7
El segundo ejemplo tiene solo una línea, cuando la solución solicitada requiere dos.
goyote

El tercer ejemplo no me funciona, probado en Chrome y Firefox.
Oliver Lorton

1
En ese ejemplo white-space: nowrap;roto lo rompe, si lo comenta, funciona.
marchitará el

42

Otra solución simple y rápida

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

La referencia a la pregunta y respuesta originales está aquí.


3
¡Solución asombrosa! No lo he probado completamente, pero al primer intento, funciona muy bien
Gambai

4
@vinesh ¡esta solución está en llamas! 🔥
PhillipJacobs

Parece que box-orientestá en desuso u obsoleto .
Greg Herbowicz

¡Trabajos! Probado esto dentro de un mat-card-contenten unflexbox container
faizanjehangir

17

El mejor que he visto, que es solo CSS y con capacidad de respuesta, proviene del Blog de desarrolladores de Mobify - Elipsis de CSS: Cómo administrar elipsis de varias líneas en CSS puro :

Ejemplo de JS Fiddle

CSS:

html, body, 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); }

HTML:

<div class="ellipsis">
    <div class="blah">
        <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>

La mejor solución que he visto hasta ahora. Es posible que desee reducir la variable de altura (200px) en el violín, para el tamaño de mi pantalla, el texto no se desbordó inicialmente.
Mike Fuchs

14

Creo que la solución de solo CSS se text-overflow: ellipsisaplica a una sola línea, por lo que no podrá seguir esta ruta:

.yourdiv {

    line-height: 1.5em; /* Sets line height to 1.5 times text size */
    height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
    width: 100%; /* Use whatever width you want */
    white-space: normal; /* Wrap lines of text */
    overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
    text-overflow: ellipsis; /* Ellipses (cross-browser) */
    -o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}

¿Has probado http://tpgblog.com/threedots/ para jQuery?


como mencioné, la combinación de puntos suspensivos con varias líneas de texto no parece funcionar, al menos no para mí en Chrome.
jackwanders

Esto funcionó en mi problema actual después añadí: display: blocky min-height: 13pxy max-height: 26pxpara el ajuste de altura para un<td>
Underverse

8

Solución CSS única para Webkit

// Only for DEMO
$(function() {

  $('#toggleWidth').on('click', function(e) {

    $('.multiLineLabel').toggleClass('maxWidth');

  });

})
.multiLineLabel {
  display: inline-block;
  box-sizing: border-box;
  white-space: pre-line;
  word-wrap: break-word;
}

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


/* Only for DEMO */

.multiLineLabel.maxWidth {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multiLineLabel">
  <span class="textMaxLine">This text is going to wrap automatically in 2 lines in case the width of the element is not sufficiently wide.</span>
</div>
<br/>
<button id="toggleWidth">Toggle Width</button>


Esta es la mejor solución y debe marcarse como una respuesta. Gracias.
QMaster

6

Solo CSS

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;


4

Normalmente, un truncado de una línea es bastante simple

.truncate-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

El truncado de dos líneas es un poco más complicado, pero se puede hacer con css, este ejemplo está en sass.

@mixin multiLineEllipsis($lineHeight: 1.2rem, $lineCount: 2, $bgColor: white, $padding-right: 0.3125rem, $width: 1rem, $ellipsis-right: 0) {
  overflow: hidden; /* hide text if it is more than $lineCount lines  */
  position: relative; /* for set '...' in absolute position */
  line-height: $lineHeight; /* use this value to count block height */
  max-height: $lineHeight * $lineCount; /* max-height = line-height * lines max number */
  padding-right: $padding-right; /* place for '...' */
  white-space: normal; /* overwrite any white-space styles */
  word-break: break-all; /* will break each letter in word */
  text-overflow: ellipsis; /* show ellipsis if text is broken */

  &::before {
    content: '...'; /* create the '...'' points in the end */
    position: absolute;
    right: $ellipsis-right;
    bottom: 0;
  }

  &::after {
    content: ''; /* hide '...'' if we have text, which is less than or equal to max lines and add $bgColor */
    position: absolute;
    right: 0;
    width: $width;
    height: 1rem * $lineCount;
    margin-top: 0.2rem;
    background: $bgColor; /* because we are cutting off the diff we need to add the color back. */
  }
}

2

Consulte http://jsfiddle.net/SWcCt/ .

Simplemente establezca line-heightla mitad de height:

line-height:20px;
height:40px;

Por supuesto, para que text-overflow: ellipsisfuncione también necesitas:

overflow:hidden;
white-space: pre;

Esta solución no es flexible y requiere un salto de línea manual en el texto fuente. Tenga en cuenta que jsfiddle.net/SWcCt/282 cada cuadro solo contiene una línea de texto. La solución deseada se vería como el segundo cuadro de jsfiddle.net/SWcCt/283 excepto con puntos suspensivos al final de la segunda línea.
Joshua Coady

@JoshuaCoady Buen punto, pero text-overflow: ellipsissolo funciona para cuadros en línea que desbordan el cuadro de línea. Sin white-space: preellos, simplemente irían al cuadro de la siguiente línea. Y luego se necesita un salto de línea manual. No creo que haya una solución perfecta.
Oriol


0

La solución de @Asiddeen bn Muhammad funcionó para mí con una pequeña modificación en el CSS

    .text {
 line-height: 1.5;
  height: 6em; 
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: block;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
 }
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.