Css text overflow string

text-overflow

CSS — свойство text-overflow задает способ оповещения пользователей о скрытом переполненном содержимом. Его можно обрезать, отображать многоточие (‘ … ‘) или отображать пользовательскую строку.

Try it

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

overflow: hidden; white-space: nowrap;

Свойство text-overflow влияет только на содержимое, которое переполняет элемент контейнера блока в направлении его встроенного продвижения (например, не переполнение текста в нижней части поля).

Syntax

Свойство text-overflow может быть указано с использованием одного или двух значений. Если задано одно значение, оно определяет поведение переполнения для конца строки (правый конец для текста слева направо, левый конец для текста справа налево). Если заданы два значения, первое указывает поведение переполнения для левого конца строки, а второе — для правого конца строки.

text-overflow: clip; text-overflow: ellipsis ellipsis; text-overflow: ellipsis " [..]"; / * Глобальные значения * / text-overflow: inherit; text-overflow: initial; text-overflow: revert; text-overflow: revert-layer; text-overflow: unset;

Values

По умолчанию для этого свойства. Это значение ключевого слова будет усекать текст на границе области содержимого , поэтому усечение может происходить в середине символа. Чтобы обрезать переход между символами, вы можете указать text-overflow в виде пустой строки, если это поддерживается в ваших целевых браузерах: text-overflow: »; ,

Это значение ключевого слова будет отображать многоточие ( ‘…’ , U+2026 HORIZONTAL ELLIPSIS ) для представления обрезанного текста. Многоточие отображается внутри области содержимого , уменьшая объем отображаемого текста. Если для отображения многоточия недостаточно места, оно обрезается.

будет использоваться для представления Обрезанного текста. Строка отображается внутри области содержимого , сокращая размер отображаемого текста. Если для отображения самой строки недостаточно места, она обрезается.

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

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

Formal definition

Formal syntax

text-overflow = clip | ellipsis

Examples

One-value syntax

В этом примере показаны разные значения для text-overflow применяемого к абзацу, для текста с направлением слева направо и справа налево.

HTML

div class="ltr"> h2>Left to right text h2> pre>clip pre> p class="overflow-clip">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>ellipsis pre> p class="overflow-ellipsis">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>" [..]" pre> p class="overflow-string">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> div> div class="rtl"> h2>Right to left text h2> pre>clip pre> p class="overflow-clip">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>ellipsis pre> p class="overflow-ellipsis">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>" [..]" pre> p class="overflow-string">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> div> 

CSS

p < width: 200px; border: 1px solid; padding: 2px 5px; / * Для переполнения текста требуются оба следующих элемента * / white-space: nowrap; overflow: hidden; > .overflow-clip < text-overflow: clip; > .overflow-ellipsis < text-overflow: ellipsis; > .overflow-string < text-overflow: " [..]"; > body < display: flex; justify-content: space-around; > .ltr > p < direction: ltr; > .rtl > p < direction: rtl; >

Result

Two-value syntax

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

Читайте также:  Chain of responsibility паттерн php

HTML

pre>clip clip pre> p class="overflow-clip-clip">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>clip ellipsis pre> p class="overflow-clip-ellipsis">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>ellipsis ellipsis pre> p class="overflow-ellipsis-ellipsis">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> pre>ellipsis " [..]" pre> p class="overflow-ellipsis-string">Lorem ipsum dolor sit amet, consectetur adipisicing elit. p> 

CSS

p < width: 200px; border: 1px solid; padding: 2px 5px; / * Для переполнения текста требуются оба следующих элемента * / white-space: nowrap; overflow: scroll; > .overflow-clip-clip < text-overflow: clip clip; > .overflow-clip-ellipsis < text-overflow: clip ellipsis; > .overflow-ellipsis-ellipsis < text-overflow: ellipsis ellipsis; > .overflow-ellipsis-string < text-overflow: ellipsis " [..]"; >

JavaScript

// Прокручиваем каждый абзац, чтобы начало также было скрыто const paras = document.querySelectorAll("p"); for (const para of paras) < para.scroll(100, 0); >

Result

Specifications

Предыдущая версия этого интерфейса достигла статуса Рекомендации кандидата . Поскольку некоторые функции, отсутствующие в списке риска, необходимо было удалить, спецификация была понижена до уровня рабочего проекта , что объясняет, почему браузеры реализовали это свойство без префикса, хотя и не в состоянии CR.

Browser compatibility

До Firefox 10 обработка text-overflow в блоках со встроенным переполнением с обеих горизонтальных сторон была некорректной. До Firefox 10, если было указано только одно значение (например, text-overflow: ellipsis; ), текст был эллиптическим с обеих сторон блока, а не только с конечного края в зависимости от направления текста блока.

До Firefox 10 обработка text-overflow в блоках со встроенным переполнением с обеих горизонтальных сторон была некорректной. До Firefox 10, если было указано только одно значение (например, text-overflow: ellipsis; ), текст был эллиптическим с обеих сторон блока, а не только с конечного края в зависимости от направления текста блока.

Источник

CSS text-overflow Property

The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user. It can be clipped, display an ellipsis (. ), or display a custom string.

Читайте также:  Python get pressed key

Both of the following properties are required for text-overflow:

Default value: clip
Inherited: no
Animatable: no. Read about animatable
Version: CSS3
JavaScript syntax: object.style.textOverflow=»ellipsis» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Numbers followed by -o- specify the first version that worked with a prefix.

CSS Syntax

Property Values

Value Description Demo
clip Default value. The text is clipped and not accessible Demo ❯
ellipsis Render an ellipsis («. «) to represent the clipped text Demo ❯
string Render the given string to represent the clipped text
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

More Examples

Example

Text-overflow with a hover effect (show entire text on hover):

div.a <
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
>

div.a:hover overflow: visible;
>

Источник

Wrapping and breaking text

This guide explains the various ways in which overflowing text can be managed in CSS.

What is overflowing text?

In CSS, if you have an unbreakable string such as a very long word, by default it will overflow any container that is too small for it in the inline direction. We can see this happening in the example below: the long word is extending past the boundary of the box it is contained in.

CSS will display overflow in this way, because doing something else could cause data loss. In CSS data loss means that some of your content vanishes. So the initial value of overflow is visible , and we can see the overflowing text. It is generally better to be able to see overflow, even if it is messy. If things were to disappear or be cropped as would happen if overflow was set to hidden you might not spot it when previewing your site. Messy overflow is at least easy to spot, and in the worst case, your visitor will be able to see and read the content even if it looks a bit strange.

In this next example, you can see what happens if overflow is set to hidden .

Finding the min-content size

To find the minimum size of the box that will contain its contents with no overflows, set the width or inline-size property of the box to min-content .

Using min-content is therefore one possibility for overflowing boxes. If it is possible to allow the box to grow to be the minimum size required for the content, but no bigger, using this keyword will give you that size.

Читайте также:  Level ranks web css v34

Breaking long words

If the box needs to be a fixed size, or you are keen to ensure that long words can’t overflow, then the overflow-wrap property can help. This property will break a word once it is too long to fit on a line by itself.

Note: The overflow-wrap property acts in the same way as the non-standard property word-wrap . The word-wrap property is now treated by browsers as an alias of the standard property.

An alternative property to try is word-break . This property will break the word at the point it overflows. It will cause a break-even if placing the word onto a new line would allow it to display without breaking.

In this next example, you can compare the difference between the two properties on the same string of text.

This might be useful if you want to prevent a large gap from appearing if there is just enough space for the string. Or, where there is another element that you would not want the break to happen immediately after.

In the example below there is a checkbox and label. Let’s say, you want the label to break should it be too long for the box. However, you don’t want it to break directly after the checkbox.

Adding hyphens

To add hyphens when words are broken, use the CSS hyphens property. Using a value of auto , the browser is free to automatically break words at appropriate hyphenation points, following whatever rules it chooses. To have some control over the process, use a value of manual , then insert a hard or soft break character into the string. A hard break ( ‐ ) will always break, even if it is not necessary to do so. A soft break ( ­ ) only breaks if breaking is needed.

You can also use the hyphenate-character property to use the string of your choice instead of the hyphen character at the end of the line (before the hyphenation line break).

This property also takes the value auto , which will select the correct value to mark a mid-word line break according to the typographic conventions of the current content language.

The element

In the below example the text breaks in the location of the .

See also

  • The HTML element
  • The CSS word-break property
  • The CSS overflow-wrap property
  • The CSS white-space property
  • The CSS hyphens property
  • Overflow and Data Loss in CSS

Found a content problem with this page?

This page was last modified on May 25, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

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