В CSS используйте «...» для переполненного блока из нескольких строк - PullRequest
300 голосов
/ 03 июня 2011

с

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

"..." будет отображаться в конце строки при переполнении.Однако это будет показано только в одной строке.Но я бы хотел, чтобы он отображался в несколько строк.

Это может выглядеть так:

Ответы [ 16 ]

84 голосов
/ 03 июня 2011

Есть также несколько плагинов jquery, которые решают эту проблему, но многие не обрабатывают несколько строк текста. Следующие работы:

Там также есть несколько тестов на соответствие .

58 голосов
/ 06 августа 2012

Я хакнул, пока мне не удалось достичь чего-то близкого к этому. Он поставляется с несколькими оговорками:

  1. Это не чистый CSS; Вы должны добавить несколько элементов HTML. Однако JavaScript не требуется.
  2. Многоточие выровнено по правому краю на последней строке. Это означает, что если ваш текст не выровнен по правому краю или не выровнен, между последним видимым словом и многоточием может быть заметный разрыв (в зависимости от длины первого скрытого слова).
  3. Место для многоточия всегда зарезервировано. Это означает, что если текст помещается в поле почти точно, он может быть излишне обрезан (последнее слово скрыто, хотя технически это не нужно).
  4. Ваш текст должен иметь фиксированный цвет фона, так как мы используем цветные прямоугольники, чтобы скрыть многоточие в тех случаях, когда это не нужно.

Следует также отметить, что текст будет прерываться на границе слова, а не на символьной границе. Это было преднамеренно (поскольку я считаю, что это лучше для более длинных текстов), но поскольку это отличается от того, что делает text-overflow: ellipsis, я подумал, что должен упомянуть об этом.

Если вы можете жить с этими предостережениями, HTML выглядит следующим образом:

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

И это соответствующий CSS, на примере блока шириной 150 пикселей с тремя строками текста на белом фоне. Предполагается, что у вас есть сброс CSS или аналогичный, который устанавливает поля и отступы в ноль, где это необходимо.

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

Результат выглядит так:

image of the rendered result with different text lengths

Чтобы пояснить, как это работает, вот то же изображение, за исключением того, что .hidedots1 выделено красным цветом, а .hidedots2 - голубым. Это прямоугольники, которые скрывают многоточие, когда нет невидимого текста:

the same image as above, except that the helper elements are highlighted in color

Протестировано в IE9, IE8 (эмулируется), Chrome, Firefox, Safari и Opera. Не работает в IE7.

41 голосов
/ 27 августа 2013

Вот недавняя статья css-tricks , в которой обсуждается это.

Некоторые решения в вышеприведенной статье (которые здесь не упомянуты):

1)-webkit-line-clamp и 2) Поместите абсолютно позиционированный элемент справа внизу с затуханием

Оба метода предполагают следующую разметку:

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

с помощью css

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

1) -webkit-line-зажим

линейный зажим FIDDLE (не более 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 */
}

2) затухание

Допустим, вы установили высоту строки в 1,2em.Если мы хотим выставить три строки текста, мы можем просто сделать высоту контейнера 3.6em (1.2em × 3).Скрытое переполнение скроет все остальное.

Исчезновение 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%);
}

Решение № 3 - комбинация с использованием @ поддерживает

Мы можем использовать @supports для применения линейного зажима webkit в браузерах webkit и применения затухания в других браузерах.

@ поддерживает line-хомут с затухающей запасной скрипкой

<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;
    }
}
34 голосов
/ 10 января 2013

Ссылка ниже предоставляет чистое HTML / CSS решение этой проблемы.

Поддержка браузера - как указано в статье:

До сих пор мы тестировали Safari 5.0, IE 9 (должен быть в стандартном режиме), Opera 12 и Firefox 15.

Старые браузеры по-прежнему будут работать достаточно хорошо, как основа макета находится в нормальных свойствах позиционирования, полей и отступов. если твой платформа старше (например, Firefox 3.6, IE 8), вы можете использовать метод, но переделайте градиент как отдельное изображение PNG или фильтр DirectX.

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

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

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>

скрипка

(изменить размер окна браузера для тестирования)

21 голосов
/ 03 июня 2011

После просмотра спецификации W3 для переполнения текста , я не думаю, что это возможно, используя только CSS. Ellipsis - это новое свойство, поэтому оно, вероятно, еще не получило широкого использования или отзывов.

Однако этот парень , похоже, задал похожий (или идентичный) вопрос, и кто-то смог придумать хорошее решение jQuery. Вы можете продемонстрировать решение здесь: http://jsfiddle.net/MPkSF/

Если javascript не подходит, я думаю, вам не повезло ...

10 голосов
/ 20 сентября 2012

Просто хочу добавить к этому вопросу для полноты картины.

  • Opera имеет нестандартную поддержку для этого, называемого -o-ellipsis-lastline .
  • dotdotdot - отличный плагин jQueryмогу порекомендовать.
8 голосов
/ 19 июля 2012

Отличный вопрос ... Хотелось бы, чтобы был ответ, но это самое близкое, что вы можете получить с помощью CSS в наши дни.Нет многоточия, но все еще довольно удобно.

overflow: hidden;
line-height: 1.2em;
height: 3.6em;      // 3 lines * line-height
7 голосов
/ 09 января 2014

Я нашел это решение css (scss), которое работает довольно хорошо. В браузерах webkit показывает многоточие, а в других браузерах просто обрезает текст. Что хорошо для моего предполагаемого использования.

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

Пример создателя: http://codepen.io/martinwolf/pen/qlFdp

6 голосов
/ 06 января 2014

Вот самое близкое решение, которое я мог бы получить, используя только 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;
}

Рабочая скрипка ( изменить размер окна, чтобы проверить )

Ссылка на мой блог для объяснения

Обновленная скрипка

Надеюсь, теперь какой-нибудь эксперт по CSS понял бы, как сделать его идеальным. :)

4 голосов
/ 09 января 2014

Немного опоздал на эту вечеринку, но я придумал, как мне кажется, уникальное решение.Вместо того, чтобы пытаться вставить свой собственный многоточие с помощью css-трюка или js, я подумал, что попробую перекатиться с ограничением в одну строку.Поэтому я дублирую текст для каждой «строки» и просто использую отрицательный текстовый отступ, чтобы убедиться, что одна строка начинается там, где заканчивается последняя. FIDDLE

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>

Подробнее вскрипкаСуществует проблема с перекомпоновкой браузера, для которой я использую перерисовку JS, и поэтому проверяйте ее, но это основная концепция.Любые мысли / предложения очень ценятся.

...