Css точки до конца строки

Как обрезать текст и добавить в конце многоточие?

Иногда приходится ограничивать длинный текст, к примеру, в блоке с фиксированными размерами, чтобы текст не выходил за пределы этого блока. Часто делается так: текст, который не помещается в заданные размеры, обрезается, а в конце текста добавляется многоточие. Оно подсказывает пользователю, что текст отображается лишь частично.

Способ обрезания текста зависит от длины и числа строк.

Однострочный текст

Для одной строки есть специальное свойство text-overflow со значением ellipsis , которое добавляет многоточие в конце текста. Чтобы это свойство работало, нужно соблюсти ещё два условия.

  1. Текст должен выводиться в одну строку без переносов. Для запрета переносов мы используем свойство white-space со значением nowrap .
  2. Текст за пределами блока скрывается от просмотра с помощью свойства overflow со значением hidden .

Комбинируя три свойства white-space, overflow и text-overflow получим обрезанную строку с многоточием в конце (пример 1).

Пример 1. Использование text-overflow

Результат данного примера показан на рис. 1.

Вид обрезанного однострочного текста

Рис. 1. Вид обрезанного однострочного текста

Многострочный текст

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

  1. Свойство -webkit-line-clamp, которое ограничивает число строк. Значение 3 отобразит три строки, значение 4 — четыре строки.
  2. Свойство display со значением -webkit-box .
  3. Свойство -webkit-box-orient со значением vertical .
  4. Свойство overflow со значением hidden , оно скрывает текст за пределами блока.

Заметьте, что в большинстве случаев мы имеем дело не со стандартными стилевыми свойствами, а добавляем к ним префикс -webkit-. При этом все эти свойства с префиксами работают даже в Firefox.

Свойство display: -webkit-box в настоящий момент устарело, при вёрстке сейчас используется display: flex . Аналогично устарело и -webkit-box-orient: vertical , сейчас вместо него применяется flex-direction: column . При этом нельзя просто заменить устаревшие свойства современными, перестанет работать ограничение строк.

Также есть проблема и с высотой блока — при добавлении padding его значение прибавляется к высоте строк, в итоге отображается часть лишней строки. Чтобы этого избежать можно явно задать высоту блока или вложить один блок внутрь другого. В примере 3 свойство padding применяется к , а набор свойств для ограничения текста к

.

Пример 2. Использование -webkit-line-clamp

Результат данного примера показан на рис. 2.

Вид обрезанного многострочного текста

Рис. 2. Вид обрезанного многострочного текста

Обратите внимание, что здесь нам не нужен text-overflow, многоточие добавляется через свойство -webkit-line-clamp.

Использование JavaScript

Если не хочется связываться с устаревшими свойствами, всегда можно воспользоваться JavaScript для решения нашей задачи. Библиотека Clamp.js позволяет выбрать алгоритм работы — с помощью -webkit-line-clamp , в этом случае применяется набор свойств из примера 2 или путём явного обрезания строки (пример 3).

Пример 3. Использование Clamp.js

Обратите внимание на параметр useNativeClamp . По умолчанию его значение равно true , в этом случае к элементу добавляется свойство -webkit-line-clamp . Если же указать значение false , тогда строка обрезается явно. Между этими алгоритмами Clamp.js есть небольшая разница, заметная при изменении размера окна браузера. Использование useNativeClamp:true обрезает строку лишь при необходимости, когда она превышает три строки. useNativeClamp:false обрезает всегда и при изменении размеров блока строка так и остаётся обрезанной.

Источник

text-overflow

The text-overflow CSS property sets how hidden overflow content is signaled to users. It can be clipped, display an ellipsis (‘ … ‘), or display a custom string.

Try it

The text-overflow property doesn’t force an overflow to occur. To make text overflow its container, you have to set other CSS properties: overflow and white-space . For example:

overflow: hidden; white-space: nowrap; 

The text-overflow property only affects content that is overflowing a block container element in its inline progression direction (not text overflowing at the bottom of a box, for example).

Syntax

text-overflow: clip; text-overflow: ellipsis ellipsis; text-overflow: ellipsis " [..]"; /* Global values */ text-overflow: inherit; text-overflow: initial; text-overflow: revert; text-overflow: revert-layer; text-overflow: unset; 

The text-overflow property may be specified using one or two values. If one value is given, it specifies overflow behavior for the end of the line (the right end for left-to-right text, the left end for right-to-left text). If two values are given, the first specifies overflow behavior for the left end of the line, and the second specifies it for the right end of the line.

Values

The default for this property. This keyword value will truncate the text at the limit of the content area, therefore the truncation can happen in the middle of a character. To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: »; .

This keyword value will display an ellipsis ( ‘…’ , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text. The ellipsis is displayed inside the content area, decreasing the amount of text displayed. If there is not enough space to display the ellipsis, it is clipped.

The to be used to represent clipped text. The string is displayed inside the content area, shortening the size of the displayed text. If there is not enough space to display the string itself, it is clipped.

This keyword clips the overflowing inline content and applies a fade-out effect near the edge of the line box with complete transparency at the edge.

This function clips the overflowing inline content and applies a fade-out effect near the edge of the line box with complete transparency at the edge.

Formal definition

Formal syntax

Источник

CSS — cut with dots (. ) overflowing text outside element

Root-ssh

In this article, we’re going to have a look at how in a simple way cut overflowing text from an element in pure CSS.

Note: JavaScript approach can be found here.

Overflowing text cut using CSS.

Practical example with explanation

The simplest way is to use text-overflow style property with ellipsis value.

This approach will be working only if:

  • element size will be defined clearly (e.g. with width style property, when some parent will exceed element size or specific layout will force element to have proper size),
  • when text wrapping will be disabled (e.g. white-space: nowrap does it),
  • content overflowing will be disabled (e.g. overflow: hidden does it).

Note: presented in this article text shortcutting does not work if display: flex style property is used with element.

To solve the display: flex problem, the text should be wrapped with additional element that uses then text-overflo: ellipsis .

Check simple the problem solution here.

Runnable practical example:

// ONLINE-RUNNER:browser;       
Very long text here, Very long text here, Very long text here, Very long text here

See also

Alternative titles

Источник

text-overflow

The text-overflow CSS property sets how hidden overflow content is signaled to users. It can be clipped, display an ellipsis (' … '), or display a custom string.

Try it

The text-overflow property doesn't force an overflow to occur. To make text overflow its container, you have to set other CSS properties: overflow and white-space . For example:

overflow: hidden; white-space: nowrap; 

The text-overflow property only affects content that is overflowing a block container element in its inline progression direction (not text overflowing at the bottom of a box, for example).

Syntax

text-overflow: clip; text-overflow: ellipsis ellipsis; text-overflow: ellipsis " [..]"; /* Global values */ text-overflow: inherit; text-overflow: initial; text-overflow: revert; text-overflow: revert-layer; text-overflow: unset; 

The text-overflow property may be specified using one or two values. If one value is given, it specifies overflow behavior for the end of the line (the right end for left-to-right text, the left end for right-to-left text). If two values are given, the first specifies overflow behavior for the left end of the line, and the second specifies it for the right end of the line.

Values

The default for this property. This keyword value will truncate the text at the limit of the content area, therefore the truncation can happen in the middle of a character. To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: ''; .

This keyword value will display an ellipsis ( '…' , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text. The ellipsis is displayed inside the content area, decreasing the amount of text displayed. If there is not enough space to display the ellipsis, it is clipped.

The to be used to represent clipped text. The string is displayed inside the content area, shortening the size of the displayed text. If there is not enough space to display the string itself, it is clipped.

This keyword clips the overflowing inline content and applies a fade-out effect near the edge of the line box with complete transparency at the edge.

This function clips the overflowing inline content and applies a fade-out effect near the edge of the line box with complete transparency at the edge.

Formal definition

Formal syntax

Источник

Читайте также:  Css animation пауза между повторениями
Оцените статью