Оберните текст внутри div всего в две строки


87

Я хочу обернуть текст только двумя строками внутри div определенной ширины. Если текст превышает длину двух строк, я хочу отображать эллипсы. Есть ли способ сделать это с помощью CSS?

например

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

благодаря

Ответы:


147

Ограничение вывода двумя строками текста возможно с помощью CSS, если вы установите line-heightи heightэлемента и установите 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 ДЕМО ---

Кроме того, вы можете использовать CSS text-overflowи white-spaceсвойства для добавления эллипсов, но это работает только для одной строки.

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

И демо:

--- jsFiddle ДЕМО ---

Получение как нескольких строк текста, так и многоточий, по-видимому, является областью javascript.


11
По какой-то причине я вижу только одну строку: /
SearchForKnowledge

7
Во втором примере всего одна строка, а для запрошенного решения требуется две.
goyote

Третий пример у меня не работает, протестирован в Chrome и Firefox.
Оливер Лортон,

1
В этом сломанном примере white-space: nowrap;он ломается, если вы его закомментируете, он работает.
Уилт

46

Еще одно простое и быстрое решение

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

Ссылка на исходный вопрос и ответ здесь


3
Замечательное решение! Я полностью не проверял, но при первой попытке, это работает очень хорошо
Gambai

4
@vinesh это решение горит! 🔥
PhillipJacobs 05


Работает! Испытано это внутри mat-card-contentвflexbox container
faizanjehangir

17

Лучшее, что я когда-либо видел и который поддерживает только CSS и адаптивно, взято из Mobify Developer Blog - CSS Ellipsis: How to Manage Multi-Line Ellipsis in Pure CSS :

Пример скрипта 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>

Лучшее решение, которое я видел до сих пор. Возможно, вы захотите уменьшить переменную высоты (200 пикселей) в скрипке, для моего размера экрана текст изначально не переполнялся.
Майк Фукс,

14

Я считаю, что решение только для CSS text-overflow: ellipsisприменимо только к одной строке, поэтому вы не сможете пойти по этому пути:

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

Вы пробовали http://tpgblog.com/threedots/ для jQuery?


Как я уже упоминал, объединение эллипсов с несколькими строками текста не работает, по крайней мере, для меня в Chrome.
jackwanders

Это работало в моей нынешней проблеме после того, как я добавил: display: blockи min-height: 13pxи max-height: 26pxдля установки высоты для<td>
Underverse

9

Единственное решение CSS для 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>


Это лучшее решение, и его следует отметить как ответ. Благодарю.
QMaster 01



4

Обычно однострочное усечение довольно просто

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

Усечение двух строк немного сложнее, но это можно сделать с помощью css, этот пример находится в 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

См. Http://jsfiddle.net/SWcCt/ .

Просто установите line-heightполовину height:

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

Конечно, для text-overflow: ellipsisработы вам также понадобятся:

overflow:hidden;
white-space: pre;

Это решение не является гибким и требует ручного разрыва строки в исходном тексте. Обратите внимание, что каждое поле jsfiddle.net/SWcCt/282 содержит только одну строку текста. Желаемое решение будет выглядеть как второе поле jsfiddle.net/SWcCt/283, за исключением того, что в конце второй строки будет отображаться многоточие.
Джошуа Коуди

@JoshuaCoady Хороший момент, но text-overflow: ellipsisработает только для встроенных блоков, которые переполняют строчный блок. Без white-space: preних просто перейти к следующему окну строки. И тогда необходим перенос строки вручную. Я не думаю, что есть идеальное решение.
Oriol


0

Решение @Asiddeen bn Muhammad сработало для меня с небольшой модификацией 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;
 }
Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.