- CSS word-break Property
- Browser Support
- CSS Syntax
- Property Values
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Wrapping and breaking text
- What is overflowing text?
- Finding the min-content size
- Breaking long words
- Adding hyphens
- The element
- See also
- Found a content problem with this page?
- word — break
- Кратко
- Пример
- Как пишется
- Особенности переноса текста
- На практике
- word-break
- Интерактивный пример
- Синтаксис
- Значения
- Формальный синтаксис
- Примеры
- HTML
- CSS
- Спецификации
- Браузерная совместимость
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
CSS word-break Property
The word-break property specifies how words should break when reaching the end of a line.
Default value: | normal |
---|---|
Inherited: | yes |
Animatable: | no. Read about animatable |
Version: | CSS3 |
JavaScript syntax: | object.style.wordBreak=»break-all» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
CSS Syntax
Property Values
Value | Description | Demo |
---|---|---|
normal | Default value. Uses default line break rules | |
break-all | To prevent overflow, word may be broken at any character | Demo ❯ |
keep-all | Word breaks should not be used for Chinese/Japanese/Korean (CJK) text. Non-CJK text behavior is the same as value «normal» | Demo ❯ |
break-word | To prevent overflow, word may be broken at arbitrary points | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
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.
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.
word — break
Что делать, если слово слишком длинное и не помещается в блок целиком?
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Свойство word — break определяет, как будет переноситься на новую строку текст при достижении края родительского контейнера.
Пример
Скопировать ссылку «Пример» Скопировано
p word-break: normal;>
p word-break: normal; >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
- normal — значение по умолчанию, длинные слова или строки с неразрывным пробелом не переносятся, даже если выходят за границы родительского блока.
- break — all — при достижении границы родительского блока перенос строки будет вставлен между любыми двумя символами.
- keep — all — перевод строки не будет использован в тексте на китайском, японском или корейском языках. Для текста на других языках будет применено normal .
- break — word (устаревшее) — разобьёт текст в любом месте, в том числе внутри слова, при достижении границы контейнера даже если доступен перенос по словам.
Свойство word — break можно глобально задать для всей страницы, добавив его в стили для селектора body .
Особенности переноса текста
Скопировать ссылку «Особенности переноса текста» Скопировано
Перенос текста в CSS происходит по определённым правилам, которые могут зависеть от языка и заданных CSS стилей (включает свойства word — break , line — break , white — space , text — align , text — justify и hyphens ). Вот некоторые правила из спецификации:
- Обязательные переносы: текст обязательно переносится на новую строку, если есть символы перевода строки (например, \n ).
- Мягкие переносы: это такие места, где текст переносится на новую строку, если он не умещается в текущей строке. Сюда относятся пробелы и другие символы-разделители. В некоторых языках между символами могут быть и другие мягкие переносы, которые зависят от языковых правил.
- Дефисы и слоги: в алфавитных языках, таких как английский и русский, слова могут быть разбиты на слоги и перенесены с использованием дефиса и языковых правил (кстати, язык определяется по HTML-атрибуту lang ). Автоматическим переносом слов с использованием дефиса управляет свойство hyphens .
- Особенности языка: некоторые языки имеют специфические правила переноса текста. В идеографических языках, таких как китайский, и слоговых языках, таких как корейский, перенос слов и разрыв строк происходит в других местах (например, между корейскими иероглифами может быть разрыв, даже если между ними нет пробела).
Когда определены возможные места переноса, подбирается подходящее место, учитывающее заданные стили. В случае с длинными словами, ссылками или другой последовательностью символов, которые не умещаются в одной строке, мы можем указать браузеру, как следует переносить текст, используя свойства overflow — wrap и word — break .
Также свойство word — break играет важную роль в CJK языках (китайский, японский и корейский): значение word — break : keep — all запрещает разрывать слова внутри CJK текста, где разрывы строк могут быть нежелательными между определёнными иероглифами.
На практике
Скопировать ссылку «На практике» Скопировано
Свойство word — break : break — all очень похоже на overflow — wrap : break — word по своей сути. Однако, есть некоторые различия в их работе.
Свойство word — break : break — all позволяет разрывать слова в любом месте, в том числе и в середине слова, чтобы уместить их в контейнере. С одной стороны, это можно привести к трудно читаемому тексту, с другой, такой перенос хорошо подходит для переноса длинных ссылок или, например, строк кода.
Свойство overflow — wrap : break — word пришло на смену word — wrap : break — word . Оно позволяет переносить длинные слова в любом месте, а не только посередине слова. Это означает, что браузер может добавить перенос слова в любом месте, если это позволяет уместить слово внутри контейнера. Это свойство также сохраняет целостность слов, если они могут поместиться внутри контейнера.
word-break
Свойство CSS word-break определяет, где будет установлен перевод на новую строку в случае превышения текстом границ блока.
Интерактивный пример
Синтаксис
/* Значения ключевых слов */ word-break: normal; word-break: break-all; word-break: keep-all; word-break: break-word; /* не включено в стандарт */ /* Глобальные значения */ word-break: inherit; word-break: initial; word-break: unset;
Свойство word-break определяется одним из описанных ниже ключевых слов.
Значения
Поведение по умолчанию для расстановки перевода строк.
При превышении границ блока, перевод строки будет вставлен между любыми двумя символами (за исключением текста на китайском/японском/корейском языке).
Перевод строки не будет использован в тексте на китайском/японском/корейском языке. Для текста на других языках будет применено поведение по умолчанию ( normal ).
При превышении границ блока, обычно остающиеся целыми слова, могут быть разбиты в произвольном месте, если не будет найдено более подходящее для переноса строки место.
Примечание: В отличие от word-break: break-word и overflow-wrap: break-word (смотри overflow-wrap ), word-break: break-all вставит перевод строки в том месте, где текст будет превышать занимаемый им блок (даже в том случае, когда текст можно перенести по словам).
Формальный синтаксис
word-break =
normal | (en-US)
keep-all | (en-US)
break-all | (en-US)
break-word
Примеры
HTML
p>1. code>word-break: normalcode>p> p class="normal narrow">This is a long and Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉p> p>2. code>word-break: break-allcode>p> p class="breakAll narrow">This is a long and Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉p> p>3. code>word-break: keep-allcode>p> p class="keepAll narrow">This is a long and Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉p> p>4. code>word-break: break-wordcode>p> p class="breakWord narrow">This is a long and Honorificabilitudinitatibus califragilisticexpialidocious Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉p>
CSS
.narrow padding: 5px; border: 1px solid; display: table; max-width: 100%; > .normal word-break: normal; > .breakAll word-break: break-all; > .keepAll word-break: keep-all; > .breakWord word-break: break-word; >
Спецификации
Specification | Status | Comment |
---|---|---|
CSS Text Module Level 3 Определение ‘word-break’ в этой спецификации. | Кандидат в рекомендации | Initial definition |
Начальное значение | normal |
---|---|
Применяется к | все элементы |
Наследуется | да |
Обработка значения | как указано |
Animation type | discrete |
Браузерная совместимость
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.