Trim text by css

Обрезаем длинную стро.

Несмотря на то, что мониторы больших диагоналей становятся всё доступнее, а их разрешение постоянно растёт, иногда возникает задача в ограниченном пространстве уместить много текста. Например, это может понадобиться для мобильной версии сайта или для интерфейса, в котором важно число строк. В подобных случаях имеет смысл обрезать длинные строки текста, оставив только начало предложения. Так мы приведём интерфейс к компактному виду и сократим объём выводимой информации. Само обрезание строк можно делать на стороне сервера с помощью того же PHP, но через CSS это проще, к тому же всегда можно показать текст целиком, например, при наведении на него курсора мыши. Далее рассмотрим методы, как текст порезать воображаемыми ножницами.

На деле всё сводится к использованию свойства overflow со значением hidden . Различия лишь кроются в разном отображении нашего текста.

Используем overflow

Чтобы свойство overflow показало себя с текстом во всей красе, надо отменить перенос текста с помощью white-space со значением nowrap . Если это не сделать, то нужного нам эффекта не будет, в тексте добавятся переносы и он будет отображаться весь целиком. В примере 1 показано, как обрезать длинный текст указанным набором стилевых свойств.

Пример 1. overflow для текста

HTML5 CSS3 IE Cr Op Sa Fx

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

Вид текста после применения свойства overflow

Рис. 1. Вид текста после применения свойства overflow

Как видно из рисунка, недостаток в целом один — не очевидно что текст имеет продолжение, так что надо дать об этом понять пользователю. Для этого обычно применяется градиент или многоточие.

Добавляем градиент к тексту

Чтобы стало понятнее, что текст справа не заканчивается, поверх него можно наложить градиент от прозрачного цвета к цвету фона (рис. 2). При этом будет создаваться эффект постепенного растворения текста.

Текст с градиентом

В примере 2 показано создание этого эффекта. Стиль самого элемента практически останется прежним, сам же градиент будем добавлять с помощью псевдоэлемента ::after и CSS3. Для этого вставляем пустой псевдоэлемент через свойство content и к нему применяем градиент с разными префиксами для основных браузеров (пример 2). Ширину градиента легко изменять через width , также можно регулировать степень прозрачности, заменив значение 0.2 на своё.

Читайте также:  Java standard library classes

Пример 2. Градиент поверх текста

HTML5 CSS3 IE 8 IE 9+ Cr Op Sa Fx

Данный метод не работает в браузере Internet Explorer до версии 8.0 включительно, потому что в нём нет поддержки градиентов. Но можно отказаться от CSS3 и сделать градиент по старинке, через картинку в формате PNG-24.

Этот метод сочетается только с однотонным фоном и в случае фоновой картинки градиент поверх текста будет бросаться в глаза.

Многоточие в конце текста

Вместо градиента в конце обрезанного текста также можно использовать многоточие. Причём оно будет добавляться автоматически с помощью свойства text-overflow . Его понимают все браузеры, включая старые версии IE, и единственным недостатком этого свойства является пока его неясный статус. В CSS3 вроде это свойство входит, но код с ним не проходит валидацию.

В примере 3 показано применение свойства text-overflow со значением ellipsis , которое добавляет многоточие. При наведении курсора мыши на текст, он отображается целиком и подсвечивается фоновым цветом.

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

HTML5 CSS3 IE Cr Op Sa Fx

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

Текст с многоточием

Рис. 3. Текст с многоточием

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

Источник

Truncate text with CSS – The Possible Ways

There are a lot of methods in every language to truncate text. But, recently, I faced a challenge on front-end in CSS, where I needed to truncate text for multiple lines. There were some situations where I was not allowed to use the JS function. So, I had to fix that through CSS. Quick Note: If you are new here: Our YouTube channel can help you to learn modern Web Development by building Real World projects fast & easy way:
Coder Champ — Subscribe Now Before diving into the exact solution, I want you to understand the properties below. I have made them easy for you, so you can quickly grab concepts.

white-space:

Consider this property as the box text handler. In simple words, when you put the text in any element, the text adjustment in that specific space depends upon the width of it. If the width of the box is 40px, and you added text into it. The text will wrap it up, according to the available white space. By default, the white-space of the box is set to normal. So, every single text which will hit the limit of 400px will wrap and shift to the next line automatically.

Читайте также:  Select стилизация css jquery

There are several different values which you can use like:

white-space: pre;
white-space: pre-wrap;
white-space: pre-line;
white-space: break-spaces;
white-space: nowrap;

text-overflow:

What do you want to do with the hidden text? The value which worked for me when I wanted to display three dots at the end of my truncated text was ellipsis. text-overflow: ellipsis; Note, this property will not work unless your box where you are putting text doesn’t have white-space and overflow: hidden; properties.

Solution # 1: Truncate text for single line

Sometimes, we want our text to be on a straight line. We can achieve it by setting a white-space property to the value nowrap. This solution works for single-line truncation. Force text to be on a single line:
white-space: nowrap; Now, our text should be on the same line and should overflow from the box if it’s long enough and wrapped before. Here is the next thing we need to tackle. We need to hide the text which is over-flowing and then add the ellipsis (three dots at the end). I will use the following properties altogether:
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

Below is a complete example of solution:

Solution # 2: Truncate text for multiple lines.

Let’s be quick and dive into the second solution, which is on multi-line. The process is straightforward; all you need is to set the height on the box or element, but here is the tricky part. We will need to count the number of lines we desire and then multiply it with line-height to get the maximum height. There are several other properties, which are necessary for this solution. You can check that into the code pen. max-height: calc(line-height * number of lines you desire);

Below is a quick example:

Do you know about this trick of CSS Multiple Box-shadows?

Added a new Video about 5 Tips to Master CSS:

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

text-box-trim examples and playground (previously known as leading-trim)

jantimon/text-box-trim-examples

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Читайте также:  Example Web Page

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

CSS Text Box Trim is a CSS property that allows you to remove the leading whitespace from a block of text. This is useful for removing the space between the top of the text and the top of the container.

🚨 text-box-trim is the new name for leading-trim : w3c/csswg-drafts#8067 (comment)

.text-box-trim < text-box-trim: both; text-box-edge: cap alphabetic; >

Animation cutting of both edges from a text

example for ascender and cap height

example for asian fonts

text-box-trim is right now only supported by Safari Technology Preview with the old leading-trim name.
But you can try it out right now in the playground

Text edge values are based of a fonts OpenType meta data. It will also be possible to define these values with css: https://www.w3.org/TR/css-fonts-5/#font-metrics-override-desc

Visualisation of the different text-box-edge values:

Talk Precise Text Alignment

Here are some cases where this property can be useful:

Centering text in buttons

Button

button < text-box-trim: both; text-box-edge: cap alphabetic; padding: 10px >

Button with leading trim

Most design systems have a spacing system that is based on multiples of a base unit. For example, a spacing system might have a base unit of 4px, and then multiples of that unit, such as 8px, 12px, 16px, etc. This is a great way to ensure that spacing is consistent across the design system.

However the added line-height destroys the spacing system:

Spacing systems without leading trim

Aligning icons with text is a common problem. With leading trim, you can align the icon with the text:

Icon

Icon with leading trim

In articles images are often placed next to images. The leading trim property allows you to remove the whitespace above the text to align the text with the image.

Image

Especially in logo design and art leading trim can be used to create aligned different text elements:

Art

  • Elika J. Etemad (fantasai) (Spec, Images, Talk)
  • Ethan Wang (Images, Talk)
  • Andrea Stan (Images)
  • Vincent De Oliveira (Button Image)
  • Kanji Database Project (Image)
  • Anton Ball (SubGrid Example)

About

text-box-trim examples and playground (previously known as leading-trim)

Источник

Оцените статью