Html word wrap break all

The definitions alone of word-break and word-wrap can easily make your head spin, but when comparing these two, specifically, it’s much easier to think of them like this:

First of all, you would probably like to use overflow: auto; as well, and you might want to try what using that alone looks like: if you can tolerate needing to scroll the text in the container rather than having arbitrary wrap positions, it might be just what you need.

Then keep in mind that in this context, a «word» is a string with no whitespaces in it.

word-break: break-all;

Prioritizes minimizing the space wasted while avoiding overflow, before keeping any words unbroken, so it never wraps anywhere but at the right margin. It even replaces line breaks with spaces in the contained text. This is useful if you want to avoid scrolling as much as possible and use a container that is enough wide for readability: however if your container is too narrow the result is in general not very satisfying, as Drkawashima noted.

word-wrap/overflow-wrap: break-word;

Prioritizes keeping any and all words unbroken while avoiding overflow, so if a word is too long to fit on the rest of the line, it wraps first and tries to fit the rest of the text on the next line even if it means leaving the line above as short as only one single character. This is useful if you want maximum readability while avoiding scrolling as much as possible and use a container that is enough wide: otherwise you might want to use only overflow: auto instead.

Regarding word-wrap, it isn’t really replaced (and maybe also more universally recognized than overflow-wrap by the browsers in use worldwide): it became an alias for overflow-wrap because all the big browsers and many many webpages had already adopted word-wrap although originally not being defined in the standards.

However, because of the widespread use, it wasn’t discarded when overflow-wrap was defined, but rather defined as the alias it is today, and for legacy reasons, UAs (User-Agents, e.g., web browsers) must treat word-wrap as a legacy name alias of the overflow-wrap property. So it has become a de facto standard of W3C and it isn’t going away any day soon (perhaps when the W3C standard becomes extinct or the entire web is universally updated by bots with AI).

5.5. Overflow Wrapping: the overflow-wrap/word-wrap property

overflow-wrap (MDN)

The word-break CSS property sets whether line breaks appear wherever the text would otherwise overflow its content box.

Try it

Syntax

/* Keyword values */
word-break: normal;
word-break: break-all;
word-break: keep-all;
word-break: break-word; /* deprecated */

/* Global values */
word-break: inherit;
word-break: initial;
word-break: revert;
word-break: revert-layer;
word-break: unset;

The word-break property is specified as a single keyword chosen from the list of values below.

Values

normal

Use the default line break rule.

break-all

To prevent overflow, word breaks should be inserted between any two characters (excluding Chinese/Japanese/Korean text).

keep-all

Word breaks should not be used for Chinese/Japanese/Korean (CJK) text. Non-CJK text behavior is the same as for normal.

break-word
Deprecated

Has the same effect as word-break: normal and overflow-wrap: anywhere, regardless of the actual value of the overflow-wrap property.

Note: In contrast to word-break: break-word and overflow-wrap: break-word (see overflow-wrap), word-break: break-all will create a break at the exact place where text would otherwise overflow its container (even if putting an entire word on its own line would negate the need for a break).

Note: While word-break: break-word is deprecated, it has the same effect, when specified, as word-break: normal and overflow-wrap: anywhere — regardless of the actual value of the overflow-wrap property.

Formal definition

Initial value normal
Applies to all elements
Inherited yes
Computed value as specified
Animation type discrete

Formal syntax

word-break = 
normal |
keep-all |
break-all |
break-word

Examples

HTML

<p>1. <code>word-break: normal</code></p>
<p class="normal narrow">
  This is a long and Honorificabilitudinitatibus califragilisticexpialidocious
  Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu
  グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉
</p>

<p>2. <code>word-break: break-all</code></p>
<p class="breakAll narrow">
  This is a long and Honorificabilitudinitatibus califragilisticexpialidocious
  Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu
  グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉
</p>

<p>3. <code>word-break: keep-all</code></p>
<p class="keepAll narrow">
  This is a long and Honorificabilitudinitatibus califragilisticexpialidocious
  Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu
  グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉
</p>

<p>4. <code>word-break: break-word</code></p>
<p class="breakWord narrow">
  This is a long and Honorificabilitudinitatibus califragilisticexpialidocious
  Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu
  グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉
</p>

CSS

.narrow {
  padding: 10px;
  border: 1px solid;
  width: 500px;
  margin: 0 auto;
  font-size: 20px;
  line-height: 1.5;
  letter-spacing: 1px;
}

.normal {
  word-break: normal;
}

.breakAll {
  word-break: break-all;
}

.keepAll {
  word-break: keep-all;
}

.breakWord {
  word-break: break-word;
}

Specifications

Specification
CSS Text Module Level 3
# word-break-property

Browser compatibility

BCD tables only load in the browser

See also

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

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

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

Вы можете использовать свойства CSS word-wrap, overflow-wrap или word-break для обертывания или переноса слов, которые в противном случае переполнили бы их контейнер. Эта статья представляет собой подробное руководство по свойствам CSS word-wrap, overflow-wrap и word-break, а также о том, как вы можете использовать их, чтобы не допустить, чтобы переполнение содержимого разрушало ваш красиво оформленный макет.

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

Как происходит перенос контента в браузерах?

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

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

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

Хотя в английских текстах для символов пробела используются мягкие обертки, для неанглийских систем письма ситуация может быть иной. Некоторые языки не используют пробелов для разделения слов. Следовательно, упаковка содержимого зависит от языка или системы письма. Значение атрибута lang, которое вы указываете в элементе html, в основном используется для определения того, какая языковая система используется. В этой статье основное внимание будет уделено системе письма на английском языке.

Переноса по умолчанию при использовании мягкой обертки может быть недостаточно, если вы имеете дело с длинным непрерывным текстом, например URL-адресами или пользовательским контентом, который у вас недостаточно или совсем не контролируется.

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

В чем разница между мягким и принудительным переносом строки?

Любой перенос текста, который происходит при использовании мягкого переноса, называется разрывом мягкого переноса. Чтобы перенос происходил при использовании мягкого обертывания, необходимо убедиться, что обертывание включено. Например, установка значения nowrap для свойства white-space отключит перенос.

С другой стороны, принудительные разрывы строк возникают из-за явного управления разрывом строк или указания конца или начала блоков текста.

CSS свойства word-wrap и overflow-wrap

Название word-wrap — это устаревшее имя свойства overflow-wrap. Word-wrap изначально было расширением Microsoft. Оно не было частью стандарта CSS, хотя большинство браузеров реализовали его под названием word-wrap. Согласно проекту спецификации CSS3, браузеры должны рассматривать word-wrap как устаревший псевдоним для свойства overflow-wrap.

В последних версиях популярных веб-браузеров реализовано свойство overflow-wrap. В проекте спецификации CSS3 указано следующее определение overflow-wrap: Это свойство указывает, может ли браузер разбивать строку на недопустимые точки переноса, чтобы предотвратить переполнение, когда неразрывная строка слишком длинна, чтобы поместиться в границах контейнера.

Если у вас есть свойство white-space для элемента, вам необходимо установить для него значение allow, чтобы разрешить эффект переноса для overflow-wrap. Ниже приведены значения свойства overflow-wrap. Вы также можете использовать глобальные значения inherit, initial, revert и unset для overflow-wrap, но здесь мы не будем их рассматривать.

overflow-wrap: normal;

overflow-wrap: anywhere;

overflow-wrap: break-word;

Ниже мы рассмотрим значения свойства CSS overflow-wrap, чтобы понять его поведение.

Normal

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

.my-element{

    overflow-wrap: normal;

}

На изображении ниже в тексте есть слово, длина которого превышает длину контейнера. Поскольку нет возможности мягкого переноса, а значение свойства overflow-wrap равно normal, слово переполняет свой контейнер. Это является поведением системы при переносе строк по умолчанию.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Anywhere

Использование значения в аnywhere приведет к разрыву неразрывной строки в произвольных точках между двумя символами. Аnywhere не будет добавлять символ дефиса, даже если вы примените свойство hyphens к этому элементу.
Браузер разорвет слово только в том случае, если отображение слова приведет к переполнению. Если слово вызывает переполнение, оно будет разорвано в точке, где это переполнение произошло.

Когда вы используете аnywhere, браузер будет учитывать возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content:

.my-element{

   overflow-wrap: anywhere;

}

В отличие от предыдущего примера, где мы использовали overflow-wrap: normal, на изображении ниже мы используем overflow-wrap :where. Слово-переполнение, которое невозможно разбить, разбивается на фрагменты текста с помощью overflow-wrap: anywhere, чтобы оно поместилось в своем контейнере.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Значение anywhere не поддерживается некоторыми браузерами. На изображении ниже показана поддержка браузерами по данным caniuse.com. Поэтому не рекомендуется использовать overflow-wrap: anywhere, если вы хотите иметь более высокую поддержку браузера.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Break-word

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

.my-element{

   overflow-wrap: break-word;

}

На изображении ниже показано, как браузер прерывает переполненный текст в предыдущем разделе, когда вы применяете overflow-wrap: break-word. Вы заметите, что изображение ниже выглядит так же, как изображение в последнем примере. Разница между overflow-wrap: anywhere и overflow-wrap: break-word заключается в вычислении внутренних размеров min-content.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Разница между anywhere и break-word очевидна при вычислении внутренних размеров min-content. С break-word браузер не учитывает возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content, но он учитывает возможности мягкого переноса при использовании anywhere.

Значение break-word имеет достойный охват среди последних версий десктопных браузеров. К сожалению, этого нельзя сказать об их мобильном аналоге. Поэтому безопаснее использовать унаследованный word-wrap: break-word вместо более нового overflow-wrap: break-word.

На изображении ниже показана поддержка браузеров overflow-wrap: break-word согласно caniuse.com. Вы заметите, что последние версии десктопных браузеров имеют поддержку, в то время как поддержка некоторых мобильных браузеров неизвестна.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Свойство Word-break

Word-break — еще одно свойство CSS, которое вы можете использовать для указания возможности мягкого переноса между символами. Вы можете использовать это свойство, чтобы разбить слово в том месте, где могло произойти переполнение, и перенести его на следующую строку.

Ниже приводится то, что говорится о свойстве CSS word-break в спецификации CSS3:

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

Это свойство определяет возможности мягкого переноса между буквами, то есть там, где это «нормально» и допустимо для разрывов строк текста. Word-break контролирует, какие типы букв браузер может объединять в неразрывные «слова», заставляя символы CJK вести себя как текст, не относящийся к CJK, или наоборот.

Ниже приведены возможные значения CSS-свойства word-break. Как и для overflow-wrap, вы также можете использовать глобальные значения inherit, initial, revert и unset, но мы не будем рассматривать их здесь:

word-break: normal;

word-break: break-all;

word-break: keep-all;

Break-word также является значением для CSS-свойства word-break, хотя оно устарело. Однако, браузеры по-прежнему поддерживают его. Указание этого свойства имеет тот же эффект, что и word-break: normal и overflow-wrap :where.

Теперь, когда мы знакомы с CSS-свойством break-word и соответствующими ему значениями, давайте подробно рассмотрим их.

Normal

Установка для свойства word-break значение normal будет применять правила разбиения по словам по умолчанию:

.my-element{

   word-break: normal;

}

На изображении ниже показано, что происходит, когда вы применяете стиль word-break: normal к блоку текста, который содержит слово длиннее, чем его контейнер. Вы видите, что в браузере действуют обычные правила разбиения на слова.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Break-all

Значение break-all вставит разрыв строки именно в том месте, где текст переполнился бы для некитайских, неяпонских и некорейских систем письма. Слово не будет помещено в отдельную строку, даже если это предотвратит необходимость вставки разрыва строки:

.my-element{

   word-break: break-all;

}

На изображении ниже я применил стиль word-break:break-all к элементу p шириной 240 пикселей, содержащему переполненный текст. Браузер вставил разрыв строки в точке, где могло произойти переполнение, и перенес оставшийся текст в следующую строку.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Использование break-all приведет к разрыву слова между двумя символами именно в том месте, где произойдет переполнение в английском и других родственных языковых системах. Однако это не применимо к текстам на китайском, японском и корейском языках (CJK).

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

На изображении ниже показана поддержка браузером word-break: break-word согласно caniuse.com. Хотя последние версии современных веб-браузеров поддерживают это значение, поддержка среди некоторых мобильных браузеров неизвестна.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Keep-all

Если вы используете значение keep-all, браузер не будет применять разрывы слов к текстам CJK, даже если происходит переполнение содержимого. Эффект от применения значения keep-all такой же, как и у normal для систем письма, отличных от CJK:

.my-element{

   word-break: keep-all;

}

На изображении ниже применение word-break: keep-all имеет тот же эффект, что и word-break: normal, потому что я использую систему письма, отличную от CJK (английский язык).

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

На изображении ниже показана поддержка браузером word-break: keep-all согласно caniuse.com. Это значение поддерживается в большинстве популярных десктопных браузеров. К сожалению, это не относится к мобильным браузерам.

Полное руководство по word-wrap, overflow-wrap и word-break в CSS

Теперь, когда мы рассмотрели свойства CSS overflow-wrap и word-break, в чем разница между ними?

В чем разница между overflow-wrap и разр word-break?

Вы можете использовать CSS свойства overflow-wrap и word-break для управления переполнением содержимого. Однако существуют различия в способах обработки этих двух свойств.

Использование overflow-wrap приведет к переносу всего переполненного слова в новую строку, если оно может поместиться в одну строку, не переполняя свой контейнер. Браузер разорвет слово только в том случае, если он не сможет разместить слово в новой строке без переполнения. В большинстве случаев свойство overflow-wrap или его устаревшее название word-wrap может быть достаточным для управления переполнением содержимого.

Свойство overflow-wrap относительно новое, поэтому его поддержка браузером ограничена. Вместо этого вы можете использовать устаревшее название word-wrap, если вам нужна более высокая поддержка браузером.

С другой стороны, word-break безжалостно разорвет слово, которое выходит за границы, между двумя символами, даже если размещение его в новой строке устранит необходимость в разрыве слова. Кроме того, некоторые системы письма, такие как системы письма CJK, имеют строгие правила разбиения по словам, которые браузер принимает во внимание при создании разрывов строк с помощью word-break.

Заключение

Как указывалось в предыдущих разделах, overflow-wrap и word-break во многом схожи. Вы можете использовать оба из них для управления разрывом строки.

Название overflow-wrap является псевдонимом устаревшего свойства word-wrap. Следовательно, вы можете использовать их как взаимозаменяемые. Однако стоит отметить, что поддержка браузером нового свойства overflow-wrap по-прежнему невысока. Вам лучше использовать word-wrap вместо overflow-wrap, если вы хотите почти универсальную поддержку браузера. Согласно проекту спецификации CSS3, браузеры должны продолжать поддерживать word-wrap.

Если вы хотите управлять переполнением содержимого, вам достаточно использовать overflow-wrap или его устаревшее название word-wrap.

Вы также можете использовать word-break, чтобы разбить слово между двумя символами, если слово выходит за пределы своего контейнера. Как и при overflow-wrap, при использовании word-break нужно действовать осторожно из-за ограничений в поддержке браузера.

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

Автор: Joseph Mawa

Источник: blog.logrocket.com

Редакция: Команда webformyself.

Читайте нас в Telegram, VK, Яндекс.Дзен

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

PSD to HTML

Практика верстки сайта на CSS Grid с нуля

Смотреть

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The word-break property in CSS is used to specify how a word should be broken or split when reaching the end of a line. The word-wrap property is used to split/break long words and wrap them into the next line.

    Difference between the “word-break: break-all;” and “word-wrap: break-word;”

    • word-break: break-all; It is used to break the words at any character to prevent overflow.
    • word-wrap: break-word; It is used to broken the words at arbitrary points to prevent overflow.

    The “word-break: break-all;” will break the word at any character so the result is to difficulty in reading whereas “word-wrap: break-word;” will split word without making the word not break in the middle and wrap it into next line.

    Example 1: This example display the break-all property values.

    <!DOCTYPE html> 

    <html

        <head

            <style

                p { 

                    width: 142px; 

                    border: 1px solid #000000; 

                

                p.gfg { 

                    word-break: break-all; 

                

            </style

        </head

        <body

            <center

                <h1 style="color:green;">GeeksforGeeks</h1

                <h2>word-break: break-all;</h2

                <p class="gfg">GeeksforGeeksGeeksGeeks. A 

                computer science portal for geeks .</p

            </center

        </body

    </html

    Output:

    Example 2: This example display the break-word property values.

    <!DOCTYPE html> 

    <html

        <head

            <style

                p { 

                    width: 140px; 

                    border: 1px solid #000000; 

                    color:black; 

                

                p.gfg { 

                    word-break: break-word; 

                

            </style

        </head

        <body

            <center

                <h1>GeeksforGeeks</h1

                <h2>word-break: break-word</h2

                <p class="gfg">GeeksforGeeksGeeksGeeks.A 

                computer science portal for geeks .</p

            </center

        </body

    </html

    Output:

    Example 3: This example display the comparison of break-all and break-word property values.

    <!DOCTYPE html>

    <html>

    <head>

        <style>

            .wb {

                word-break: break-all;

                width: 140px; 

                border: 1px solid green;

            }

            .wr {

                word-wrap: break-word;

                width: 140px; 

                border: 1px solid green;

            }

            .main1 {

                width:50%;

                float:left;

            }

            .main2 {

                width:50%;

                float:left;

            }

        </style>

    </head>

    <body>

        <center>

            <h1>GeeksforGeeks</h1>

            <div style = "width:100%;">

                <div class = "main1">

                    <h2>word-break: break-all:</h2>

                    <div class="wb">

                        Prepare for the Recruitment drive of product

                        based companies like Microsoft, Amazon, Adobe

                        etc with a free online placement preparation

                        course. The course focuses on various MCQ's

                        & Coding question likely to be asked in the

                        interviews & make your upcoming placement

                        season efficient and successful.

                    </div>

                </div>

                <div class = "main2">

                    <h2>word-wrap: break-word:</h2>

                    <div class="wr">

                        Prepare for the Recruitment drive of product

                        based companies like Microsoft, Amazon, Adobe

                        etc with a free online placement preparation

                        course. The course focuses on various MCQ's

                        & Coding question likely to be asked in the

                        interviews & make your upcoming placement

                        season efficient and successful.

                    </div>

                </div>

            </div>

        </center>

    </body>

    </html>                    

    Output:

    Like Article

    Save Article

    Let’s talk about the various ways we can control how text wraps (or doesn’t wrap) on a web page. CSS gives us a lot of tools to make sure our text flows the way we want it to, but we’ll also cover some tricks using HTML and special characters.

    Box wrapped with long ribbon

    Protecting Layout

    Normally, text flows to the next line at “soft wrap opportunities”, which is a fancy name for spots you’d expect text to break naturally, like between words or after a hyphen. But sometimes you may find yourself with long spans of text that don’t have soft wrap opportunities, such as really long words or URLs. This can cause all sorts of layout issues. For example, the text may overflow its container, or it might force the container to become too wide and push things out of place.

    It’s good defensive coding to anticipate issues from text not breaking. Fortunately, CSS gives us some tools for this.

    Getting Overflowing Text to Wrap

    Putting overflow-wrap: break-word on an element will allow text to break mid-word if needed. It’ll first try to keep a word unbroken by moving it to the next line, but will then break the word if there’s still not enough room.

    See the Pen overflow-wrap: break-word by Will Boyd (@lonekorean) on CodePen.

    There’s also overflow-wrap: anywhere, which breaks words in the same manner. The difference is in how it affects the min-content size calculation of the element it’s on. It’s pretty easy to see when width is set to min-content.

    .top {
    width: min-content;
    overflow-wrap: break-word;
    }

    .bottom {
    width: min-content;
    overflow-wrap: anywhere;
    }

    See the Pen overflow-wrap + min-content by Will Boyd (@lonekorean) on CodePen.

    The top element with overflow-wrap: break-word calculates min-content as if no words are broken, so its width becomes the width of the longest word. The bottom element with overflow-wrap: anywhere calculates min-content with all the breaks it can create. Since a break can happen, well, anywhere, min-content ends up being the width of a single character.

    Remember, this behavior only comes into play when min-content is involved. If we had set width to some rigid value, we’d see the same word-breaking result for both.

    Breaking Words without Mercy

    Another option for breaking words is word-break: break-all. This one won’t even try to keep words whole — it’ll just break them immediately. Take a look.

    See the Pen word-break: break-all by Will Boyd (@lonekorean) on CodePen.

    Notice how the long word isn’t moved to the next line, like it would have been when using overflow. Also notice how “words” is broken, even though it would have fit just fine on the next line.

    word-break: break-all has no problem breaking words, but it’s still cautious around punctuation. For example, it’ll avoid starting a line with the period from the end of a sentence. If you want truly merciless breaking, even with punctuation, use line-break: anywhere.

    See the Pen word-break: break-all vs line-break: anywhere by Will Boyd (@lonekorean) on CodePen.

    See how word-break: break-all moves the “k” down to avoid starting the second line with “.”? Meanwhile, line-break: anywhere doesn’t care.

    Excessive Punctuation

    Let’s see how the CSS properties we’ve covered so far handle excessively long spans of punctuation.

    See the Pen Excessive Punctuation by Will Boyd (@lonekorean) on CodePen.

    overflow-wrap: break-word and line-break: anywhere are able to keep things contained, but then there’s word-break: break-all being weird with punctuation again — this time resulting in overflowing text.

    It’s something to keep in mind. If you absolutely do not want text to overflow, be aware that word-break: break-all won’t stop runaway punctuation.

    Specifying Where Words Can Break

    For more control, you can manually insert word break opportunities into your text with <wbr>. You can also use a “zero-width space”, provided by the &ZeroWidthSpace; HTML entity (yes, it must be capitalized just as you see it!).

    Let’s see these in action by wrapping a long URL that normally wouldn’t wrap, but only between segments.

      <!-- normal -->
    <p>https://subdomain.somewhere.co.uk</p>

    <!-- <wbr> -->
    <p>https://subdomain<wbr>.somewhere<wbr>.co<wbr>.uk</p>

    <!-- &ZeroWidthSpace; -->
    <p>https://subdomain&ZeroWidthSpace;.somewhere&ZeroWidthSpace;.co&ZeroWidthSpace;.uk</p>

    See the Pen Manual Word Break Opportunities by Will Boyd (@lonekorean) on CodePen.

    Automatic Hyphenation

    You can tell the browser to break and hyphenate words where appropriate by using hyphens: auto. Hyphenation rules are determined by language, so you’ll need to tell the browser what language to use. This is done by specifying the lang attribute in HTML, possibly on the relevant element directly, or on <html>.

    <p lang="en">This is just a bit of arbitrary text to show hyphenation in action.</p>
      p {
    -webkit-hyphens: auto; /* for Safari */
    hyphens: auto;
    }

    See the Pen hyphens: auto by Will Boyd (@lonekorean) on CodePen.

    Manual Hyphenation

    You can also take matters into your own hands and insert a “soft hyphen” manually with the &shy; HTML entity. It won’t be visible unless the browser decides to wrap there, in which case a hyphen will appear. Notice in the following demo how we’re using &shy; twice, but we only see it once where the text wraps.

    <p lang="en">Magic? Abraca&shy;dabra? Abraca&shy;dabra!</p>

    See the Pen Soft Hyphen by Will Boyd (@lonekorean) on CodePen.

    hyphens must be set to either auto or manual for &shy; to display properly. Conveniently, the default is hyphens: manual, so you should be good without any additional CSS (unless something has declared hyphens: none for some reason).

    Preventing Text from Wrapping

    Let’s switch things up. There may be times when you don’t want text to wrap freely, so that you have better control over how your content is presented. There are a couple of tools to help you with this.

    First up is white-space: nowrap. Put it on an element to prevent its text from wrapping naturally.

    See the Pen white-space: nowrap by Will Boyd (@lonekorean) on CodePen.

    Preformatting Text

    There’s also white-space: pre, which will wrap text just as you have it typed in your HTML. Be careful though, as it will also preserve spaces from your HTML, so be mindful of your formatting. You can also use a <pre> tag to get the same results (it has white-space: pre on it by default).

    <!-- the formatting of this HTML results in extra whitespace! -->
    <p>
    What's worse, ignorance or apathy?
    I don't know and I don't care.
    </p>

    <!-- tighter formatting that "hugs" the text -->
    <p>What's worse, ignorance or apathy?
    I don't know and I don't care.</p>

    <!-- same as above, but using <pre> -->
    <pre>What's worse, ignorance or apathy?
    I don't know and I don't care.</pre>

    p {
    white-space: pre;
    }

    pre {
    /* <pre> sets font-family: monospace, but we can undo that */
    font-family: inherit;
    }

    See the Pen Preformatted Text by Will Boyd (@lonekorean) on CodePen.

    A Break, Where Words Can’t Break?

    For line breaks, you can use <br> inside of an element with white-space: nowrap or white-space: pre just fine. The text will wrap.

    But what happens if you use <wbr> in such an element? Kind of a trick question… because browsers don’t agree. Chrome/Edge will recognize the <wbr> and potentially wrap, while Firefox/Safari won’t.

    When it comes to the zero-width space (&ZeroWidthSpace;) though, browsers are consistent. None will wrap it with white-space: nowrap or white-space: pre.

    <p>Darth Vader: Nooooooooooooo<br>oooo!</p>

    <p>Darth Vader: Nooooooooooooo<wbr>oooo!</p>

    <p>Darth Vader: Nooooooooooooo&ZeroWidthSpace;oooo!</p>

    See the Pen white-space: nowrap + breaking lines by Will Boyd (@lonekorean) on CodePen.

    Non-Breaking Spaces

    Sometimes you may want text to wrap freely, except in very specific places. Good news! There are a few specialized HTML entities that let you do exactly this.

    A “non-breaking space” (&nbsp;) is often used to keep space between words, but disallow a line break between them.

    <p>Something I've noticed is designers don't seem to like orphans.</p>

    <p>Something I've noticed is designers don't seem to like&nbsp;orphans.</p>

    See the Pen Non-Breaking Space by Will Boyd (@lonekorean) on CodePen.

    Word Joiners and Non-Breaking Hyphens

    It’s possible for text to naturally wrap even without spaces, such as after a hyphen. To prevent wrapping without adding a space, you can use &NoBreak; (case-sensitive!) to get a “word joiner”. For hyphens specifically, you can get a “non-breaking hyphen” with (it doesn’t have a nice HTML entity name).

      <p>Turn right here to get on I-85.</p>

    <p>Turn right here to get on I-&NoBreak;85.</p>

    <p>Turn right here to get on I85.</p>

    See the Pen Word Joiners and Non-Breaking Hyphens by Will Boyd (@lonekorean) on CodePen.

    CJK Text and Breaking Words

    CJK (Chinese/Japanese/Korean) text behaves differently than non-CJK text in some ways. Certain CSS properties and values can be used for additional control over the wrapping of CJK text specifically.

    Default browser behavior allows words to be broken in CJK text. This means that word-break: normal (the default) and word-break: break-all will give you the same results. However, you can use word-break: keep-all to prevent CJK text from wrapping within words (non-CJK text will be unaffected).

    Here’s an example in Korean. Note how the word “자랑스럽게” does or doesn’t break.

    See the Pen CJK Text + word-break by Will Boyd (@lonekorean) on CodePen.

    Be careful though, Chinese and Japanese don’t use spaces between words like Korean does, so word-break: keep-all can easily cause long overflowing text if not otherwise handled.

    CJK Text and Line Break Rules

    We talked about line-break: anywhere earlier with non-CJK text and how it has no problem breaking at punctuation. The same is true with CJK text.

    Here’s an example in Japanese. Note how “。” is or isn’t allowed to start a line.

    See the Pen CJK Text + line-break by Will Boyd (@lonekorean) on CodePen.

    There are other values for line-break that affect how CJK text wraps: loose, normal, and strict. These values instruct the browser on which rules to use when deciding where to insert line breaks. The W3C describes several rules and it’s possible for browsers to add their own rules as well.

    Worth Mentioning: Element Overflow

    The overflow CSS property isn’t specific to text, but is often used to ensure text doesn’t render outside of an element that has its width or height constrained.

    .top {
    white-space: nowrap;
    overflow: auto;
    }

    .bottom {
    white-space: nowrap;
    overflow: hidden;
    }

    See the Pen Element Overflow by Will Boyd (@lonekorean) on CodePen.

    As you can see, a value of auto allows the content to be scrolled (auto only shows scrollbars when needed, scroll shows them always). A value of hidden simply cuts off the content and leaves it at that.

    overflow is actually shorthand to set both overflow-x and overflow-y, for horizontal and vertical overflow respectively. Feel free to use what suits you best.

    We can build upon overflow: hidden by adding text-overflow: ellipsis. Text will still be cut off, but we’ll get some nice ellipsis as an indication.

    p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    }

    See the Pen text-overflow: ellipsis by Will Boyd (@lonekorean) on CodePen.

    Bonus Trick: Pseudo-Element Line Break

    You can force a line break before and/or after an inline element, while keeping it as an inline element, with a little bit of pseudo-element trickery.

    First, set the content of a ::before or ::after pseudo-element to 'A', which will give you the new line character. Then set white-space: pre to ensure the new line character is respected.

    <p>Things that go <span>bump</span> in the night.</p>
    span {
    background-color: #000;
    }

    span::before, span::after {
    content: 'A';
    white-space: pre;
    }

    See the Pen Pseudo-Element Line Breaks by Will Boyd (@lonekorean) on CodePen.

    We could have just put display: block on the <span> to get the same breaks, but then it would no longer be inline. The background-color makes it easy to see that with this method, we still have an inline element.

    Bonus Notes

    • There’s an older CSS property named word-wrap. It’s non-standard and browsers now treat it as an alias for overflow-wrap.
    • The white-space CSS property has some other values we didn’t cover: pre-wrap, pre-line, and break-spaces. Unlike the ones we did cover, these don’t prevent text wrapping.
    • The CSS Text Module Level 4 spec describes a text-wrap CSS property that looks interesting, but at the time of writing, no browser implements it.

    Time to “Wrap” Things Up

    There’s so much that goes into flowing text on a web page. Most of the time you don’t really need to think about it, since browsers handle it for you. For the times when you do need more control, it’s nice to know that you have a lot of options.

    Writing this was definitely a rabbit hole for me as I kept finding more and more things to talk about. I hope I’ve shown you enough to get your text to break and flow just the way you want it.

    Thanks for reading!

    Понравилась статья? Поделить с друзьями:
  • Html word spacing normal
  • Html word 2007 как
  • Html to word для php
  • Html from word doc формат
  • Html to word with php