Avvolgi un testo in sole due righe all'interno di div


87

Voglio avvolgere un testo all'interno di sole due righe all'interno di div di larghezza specifica. Se il testo supera la lunghezza di due righe, voglio mostrare le ellissi. C'è un modo per farlo usando i CSS?

per esempio

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

Grazie

Risposte:


147

Limitare l'output a due righe di testo è possibile con i CSS, se si impostano i line-heighte heightdell'elemento e si imposta 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 ---

In alternativa, puoi utilizzare il CSS text-overflowe le white-spaceproprietà per aggiungere puntini di sospensione, ma questo sembra funzionare solo per una singola riga.

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

E una demo:

--- jsFiddle DEMO ---

Il raggiungimento di più righe di testo ed ellissi sembra essere il regno di javascript.


11
Vedo solo una riga che attraversa per qualche motivo: /
SearchForKnowledge

7
Il secondo esempio ha una sola riga, quando la soluzione richiesta ne richiede due.
goyote

Il terzo esempio non funziona per me, testato in Chrome e Firefox.
Oliver Lorton

1
In quell'esempio rotto white-space: nowrap;lo interrompe, se lo commentate funziona.
Wilt

46

Un'altra soluzione semplice e veloce

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

Il riferimento alla domanda e alla risposta originali è qui


3
Soluzione straordinaria! Non l'ho testato completamente, ma al primo tentativo funziona molto bene
Gambai

4
@vinesh questa soluzione è in fiamme! 🔥
PhillipJacobs

Sembra box-orientè disapprovato o obsoleto .
Greg Herbowicz

Lavori! Testato all'interno di un mat-card-contentin aflexbox container
faizanjehangir

17

Il migliore che ho visto, che è solo CSS e reattivo, proviene da Mobify Developer Blog - CSS Ellipsis: How to Manage Multi-Line Ellipsis in Pure CSS :

Esempio di violino JS

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 migliore soluzione che ho visto finora. Potresti voler ridurre la variabile di altezza (200px) nel violino, per le dimensioni dello schermo il testo non è stato traboccato inizialmente.
Mike Fuchs

14

Credo che la soluzione solo CSS si text-overflow: ellipsisapplichi a una sola riga, quindi non sarai in grado di seguire questa strada:

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

Hai provato http://tpgblog.com/threedots/ per jQuery?


come ho detto, la combinazione di puntini di sospensione con più righe di testo non sembra funzionare, almeno non per me in Chrome.
jackwanders

Questo ha funzionato nel mio problema attuale dopo aver aggiunto: display: blockand min-height: 13pxe max-height: 26pxper l'impostazione dell'altezza per un<td>
Underverse

9

Soluzione unica CSS per 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>


Questa è la soluzione migliore e deve essere contrassegnata come risposta. Grazie.
QMaster

7

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

Tipicamente un troncamento di una riga è abbastanza semplice

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

Il troncamento di due righe è un po 'più complicato, ma può essere fatto con css, questo esempio è in 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

Vedi http://jsfiddle.net/SWcCt/ .

Basta impostare line-heightla metà di height:

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

Certo, per poter text-overflow: ellipsislavorare hai anche bisogno di:

overflow:hidden;
white-space: pre;

Questa soluzione non è flessibile e richiede un'interruzione di riga manuale nel testo di origine. Nota che jsfiddle.net/SWcCt/282 ogni casella contiene solo una riga di testo. La soluzione desiderata sarebbe simile alla seconda casella di jsfiddle.net/SWcCt/283 tranne con i puntini di sospensione alla fine della seconda riga.
Joshua Coady

@JoshuaCoady Buon punto, ma text-overflow: ellipsisfunziona solo per le caselle in linea che superano la casella di riga. Senza white-space: preandrebbero semplicemente alla casella della riga successiva. E quindi è necessaria un'interruzione di riga manuale. Non credo che ci sia una soluzione perfetta.
Oriol


0

La soluzione di @Asiddeen bn Muhammad ha funzionato per me con una piccola modifica al 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;
 }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.