Word breaking in html

Свойство 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

Поведение по умолчанию для расстановки перевода строк.

break-all

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

keep-all

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

break-word
Non-standard

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

Примечание: В отличие от 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: 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: 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

Internet Explorer Chrome Opera Safari Firefox Android iOS
5.5+ 1.0+ 3.1 15.0+ 2.0+ 2.0+

Краткая информация

Значение по умолчанию normal
Наследуется Да
Применяется Ко всем элементам
Процентная запись Неприменима
Ссылка на спецификацию http://dev.w3.org/csswg/css3-text/#word-break

Версии CSS

CSS 1 CSS 2 CSS 2.1 CSS 3

Описание

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

Синтаксис

word-break: normal | break-all | keep-all

Значения

normal
Используются правила переноса строк по умолчанию. Как правило, в этом случае строки не переносятся или переносятся в тех местах, где явно задан перенос (например, с помощью тега <br>).
break-all
Перенос строк добавляется автоматически, чтобы слово поместилось в заданную ширину блока. Значение не работает для текста на китайском, корейском или японском языке.
keep-all
Не разрешает перенос строк в словах на китайском, корейском или японском языке. Для остальных языков действует как normal.

Пример

HTML5CSS3IECrOpSaFx 15

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>word-break</title>
  <style>
   .col { 
    background: #f0f0f0; /* Цвет фона */
    width: 180px; /* Ширина блока */
    padding: 10px; /* Поля */
    word-break: break-all; /* Перенос слов */ 
   }
  </style>
 </head>
 <body> 
  <div class="col">
   <p>Cуществительное</p>
   <p>высокопревосходительство</p>
   <p>Одушевленное существительное</p>
   <p>одиннадцатиклассница</p>
   <p>Химическое вещество</p>
   <p>метоксихлордиэтиламинометилбутиламиноакридин</p>
  </div>
 </body>
</html>

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

Перенос длинных слов

Рис. 1. Перенос длинных слов

CSS по теме

Статьи по теме

Рецепты CSS

screenshot

When the text in <p> tag is too long, it appears like this, how to prevent this with CSS? I’ve tried the CSS property word-break: break-all; but Firefox and Opera doesn’t support this property, and besides that other «normal» words also breaking. So I want to break only very long words, but not short words, depending on width of white <div>.

body {
    background-color: #ccc;
}
h2 {
    float: left;
    color: #525254;
    margin: 0px;
    font: bold 15px Arial, Helvetica, sans;
}
.post {
    background-color: #fff;
    float: left;
    clear: both;
    padding: 20px;
    width: 500px;
    border-bottom: solid 1px #ddd;
}
.post_cell {
    display: table-cell;
    vertical-align: middle;
}
.post_body {
    display: table-cell;
    width: 400px;
    opacity: 0.8;
}
.profile_img {
    border: solid 3px #ccc;
    width: 48px;
    height: 48px;
    margin: 0px 15px;
}
.post_info {
    color: #c3c3c3;
    font: normal 12px Arial, Helvetica, sans;
    margin-left: 8px;
}
a.no_style {
    color: inherit;
    text-decoration: inherit;
    font: inherit;
}
p {
    float: left;
    clear: both;
    color: #525254;
    margin: 0px;
    padding: 0px;
    line-height: 18px;
    font: normal 15px Arial, Helvetica, sans;
    word-wrap: break-word;
}
<div class="post">
    <div class="post_cell">
        <input type="checkbox" />
    </div>
    <div class="post_cell">
        <img class="profile_img" src="" height="48">
    </div>
    <div class="post_body">
        <div class="post_details">
            <h2>
                <a href="javascript:void(0)" target="_blank" class="no_style">user</a>
            </h2>
            <span class="post_info">
                <span class="passed_time">15 hours ago</span> | 
                <a href="javascript:void(0)" class="no_style">3 Comments</a>
            </span>
        </div>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
    </div>
</div>

You can check out this for more: http://jsfiddle.net/Le4zK/16/

TylerH's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

asked Sep 10, 2011 at 8:58

haynar's user avatar

2

Write this word-wrap: break-word; instead of word-break: break-all;

EDIT :

Maybe this a bug with display:table property. I did some changes in css:
Put display:table in parent div.

.post{
    background-color: #fff;
    float: left;
    clear: both;
    padding: 20px;
    width: 500px;
    border-bottom: solid 1px #ddd;
    display:table;
}

Remove display:table-cell from .post_body css:

.post_body{
    width: 580px;
    opacity: 0.8;
}

Check if this example works for you.

Toon Krijthe's user avatar

Toon Krijthe

52.7k38 gold badges146 silver badges202 bronze badges

answered Sep 10, 2011 at 9:06

sandeep's user avatar

sandeepsandeep

90.8k23 gold badges136 silver badges155 bronze badges

1

Long ago I tried to solve this problem and I couldn’t find any css only cross-browser solution so I ended up inserting zero-width spaces into long words using javascript:

var breakableLongWord = '';
for( var i = 0; i < longWord.length; i += 10 ) {
    if( i ) breakableLongWord += String.fromCharCode( 8203 );
    breakableLongWord += longWord.substr( i, 10 );
}

As I said it was long ago so you might be able to find a better solution with newer browser technologies.

answered Sep 10, 2011 at 9:35

nobody's user avatar

nobodynobody

10.5k4 gold badges25 silver badges42 bronze badges

2

The right property is word-wrap: break-word.

You can specify either normal or break-word value with the word-wrap property. normal means the text will extend the boundaries of the box. break-word means the text will wrap to next line.

word-wrap is supported in IE 5.5+, Firefox 3.5+, and WebKit browsers such as Chrome and Safari.

answered Sep 10, 2011 at 9:11

Simone's user avatar

SimoneSimone

19.9k13 gold badges78 silver badges101 bronze badges

4

In the JSFiddle here jsfiddle.net/Le4zK, your <p> is floated left. For starters, remove this. Also, .post_body has a display of table-cell. Remove this. Then you will see that the word-wrap is respected but your <p> is too big at 580px.

Try and avoid using the table-cell layouts where possible, as from the example given it isn’t particularly needed.

answered Sep 10, 2011 at 10:18

Hux's user avatar

HuxHux

3,0921 gold badge26 silver badges33 bronze badges

2

Check this solution.

The problem was the <p> tag length. Giving it a percentage width based on the parent with position set to relative seems to fix the issue. I also wrapped the content in another div.

The trick is to contain all the long element inside a parent div, since you are altering the display properties and using floating, this will keep the content flow normal for the elements inside the divs.

answered Sep 10, 2011 at 10:33

Jose Faeti's user avatar

Jose FaetiJose Faeti

12.1k5 gold badges39 silver badges52 bronze badges

1

I would use overflow-x: hidden on your parent container.

answered Sep 10, 2011 at 9:40

vise's user avatar

visevise

12.5k11 gold badges52 silver badges63 bronze badges

2

Example

Break words at any character:

p.a {
  word-break: break-all;
}

Try it Yourself »


Definition and Usage

The word-break property specifies how words
should break when reaching the end of a line.

Show demo ❯

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.

Property
word-break 4.0 5.5 15.0 3.1 15.0

CSS Syntax

word-break: normal|break-all|keep-all|break-word|initial|inherit;

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

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

Краткая информация

Значение по умолчанию normal
Наследуется Да
Применяется Ко всем элементам
Анимируется Нет

Синтаксис

word-break: normal | break-all | keep-all

Синтаксис

Описание Пример
<тип> Указывает тип значения. <размер>
A && B Значения должны выводиться в указанном порядке. <размер> && <цвет>
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,<время>]*
+ Повторять один или больше раз. <число>+
? Указанный тип, слово или группа не является обязательным. inset?
{A, B} Повторять не менее A, но не более B раз. <радиус>{1,4}
# Повторять один или больше раз через запятую. <время>#

Значения

normal
Используются правила переноса строк по умолчанию. Как правило, в этом случае строки не переносятся или переносятся в тех местах, где явно задан перенос (например, с помощью <br>).
break-all
Перенос строк добавляется автоматически, чтобы слово поместилось в заданную ширину блока. Значение не работает для текста на китайском, корейском или японском языке.
keep-all
Не разрешает перенос строк в словах на китайском, корейском или японском языке. Для остальных языков действует как normal.

Пример

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>word-break</title>
<style>
.col {
background: #f0f0f0; /* Цвет фона */
width: 180px; /* Ширина блока */
padding: 10px; /* Поля */
word-break: break-all; /* Перенос слов */
}
</style>
</head>
<body>
<div class=»col»>
<p>Cуществительное</p>
<p>высокопревосходительство</p>
<p>Одушевленное существительное</p>
<p>одиннадцатиклассница</p>
<p>Химическое вещество</p>
<p>метоксихлордиэтиламинометилбутиламиноакридин</p>
</div>
</body>
</html>

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

Перенос длинных слов

Рис. 1. Перенос длинных слов

Объектная модель

Объект.style.wordBreak

Примечание

Chrome до версии 44, Opera до версии 31, Safari до версии 9, Android и Opera Mobile не поддерживают значение keep-all.

Спецификация

Спецификация Статус
CSS Text Level 3 Рабочий проект

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation (Рекомендация) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation (Возможная рекомендация) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation (Предлагаемая рекомендация) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft (Рабочий проект) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft (Редакторский черновик) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft (Черновик спецификации) — первая черновая версия стандарта.

Браузеры

5.5 12 1 44 15 31 3.1 9 15
2.1 15 37 3.2 9.2

Браузеры

В таблице браузеров применяются следующие обозначения.

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

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

The word-break property specifies where the lines should be broken.

Normally, line breaks only occur in certain spaces when there is a space or a hyphen. But when the word-break property is set to the break-all value, the browser will break lines at any point.

This property is one of the CSS3 properties.

word-break: normal | break-all | keep-all | break-word | initial | inherit;

Example of the word-break property:

<!DOCTYPE html>
<html>
  <head>
    <title>The title of the document</title>
    <style>
      html,
      body {
        height: 100%;
      }
      body {
        font-family: Helvetica, san serif;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #8ebf42;
      }
      p {
        word-break: break-all;
        line-height: 1;
        text-transform: uppercase;
        text-align: center;
        font-size: 30px;
        font-weight: bold;
        color: #eee;
        width: 1em;
      }
    </style>
  </head>
  <body>
    <p>element</p>
  </body>
</html>

Result

CSS word-break Property

In the following example the words break in the text.

Example of the word-break property with the «break-all» value:

<!DOCTYPE html>
<html>
  <head>
    <title>The title of the document</title>
    <style>
      body {
        font-size: 0.95em;
        line-height: 1.5;
        font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
      }
      .container {
        margin: 50px auto;
        max-width: 700px;
      }
      .text {
        padding: 20px;
        background-color: #666;
        color: white;
        text-align: justify;
      }
      .break {
        word-break: break-all;
      }
      strong {
        background-color: #000;
      }
    </style>
  </head>
  <body>
    <h2>Word-break property example</h2>
    <div class="container">
      <h3>Text breaks inside words</h3>
      <p class="text break">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem <strong>Ipsum</strong> has been the industry's standard dummy text ever since the 1500s, when an <strong>unknown</strong> printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, <strong>remaining</strong> essentially unchanged.
      </p>
    </div>
  </body>
</html>

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

Демо¶

Текст

  • hanging-punctuation
  • hyphens
  • letter-spacing
  • line-break
  • overflow-wrap
  • paint-order
  • tab-size
  • text-align
  • text-align-last
  • text-indent
  • text-justify
  • text-size-adjust
  • text-transform
  • white-space
  • word-break
  • word-spacing
  • letter-spacing
  • text-decoration
  • text-decoration-color
  • text-decoration-line
  • text-decoration-style
  • text-decoration-thickness
  • text-decoration-skip
  • text-decoration-skip-ink
  • text-emphasis
  • text-emphasis-color
  • text-emphasis-position
  • text-emphasis-style
  • text-indent
  • text-rendering
  • text-shadow
  • text-underline-position
  • text-transform
  • white-space
  • word-spacing

Синтаксис¶

word-break: normal;
word-break: break-all;
word-break: keep-all;

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

Значения¶

normal
Используются правила переноса строк по умолчанию. Как правило, в этом случае строки не переносятся или переносятся в тех местах, где явно задан перенос (например, с помощью <br>).
break-all
Перенос строк добавляется автоматически, чтобы слово поместилось в заданную ширину блока. Значение не работает для текста на китайском, корейском или японском языке.
keep-all
Не разрешает перенос строк в словах на китайском, корейском или японском языке. Для остальных языков действует как normal.

Значение по-умолчанию: normal

Применяется ко всем элементам

Спецификации¶

  • CSS Text Level 3

Поддержка браузерами¶

Can I Use word-break? Data on support for the word-break feature across the major browsers from caniuse.com.

Описание и примеры¶

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>word-break</title>
    <style>
      .col {
        background: #f0f0f0; /* Цвет фона */
        width: 180px; /* Ширина блока */
        padding: 10px; /* Поля */
        word-break: break-all; /* Перенос слов */
      }
    </style>
  </head>
  <body>
    <div class="col">
      <p>Cуществительное</p>
      <p>высокопревосходительство</p>
      <p>Одушевленное существительное</p>
      <p>одиннадцатиклассница</p>
      <p>Химическое вещество</p>
      <p>метоксихлордиэтиламинометилбутиламиноакридин</p>
    </div>
  </body>
</html>

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

The word-break property in CSS can be used to change when line breaks ought to occur. Normally, line breaks in text can only occur in certain spaces, like when there is a space or a hyphen.

In the example below we can make the word-break between letters instead:

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

If we then set the width of the text to one em, the word will break by each letter:

See the Pen Setting text vertically with word-break by CSS-Tricks (@css-tricks) on CodePen.

This value is often used in places with user generated content so that long strings don’t risk breaking the layout. One very common example is a long copy and pasted URL. If that URL has no hyphens, it can extend beyond the parent box and look bad or worse, cause layout problems.

See the Pen Fixing links with word-break by CSS-Tricks (@css-tricks) on CodePen.

Values

  • normal: use the default rules for word breaking.
  • break-all: any word/letter can break onto the next line.
  • keep-all: for Chinese, Japanese and Korean text words are not broken. Otherwise this is the same as normal.

This property is also often used in conjunction with the hyphens property so that when breaks occur a hypen is inserted, as per the standard in books.

The full usage, with needed vendor prefixes, is:

 -ms-word-break: break-all;
     word-break: break-all;

     /* Non standard for WebKit */
     word-break: break-word;

-webkit-hyphens: auto;
   -moz-hyphens: auto;
        hyphens: auto;

Using these properties on the universal selector can be useful if you have a site with a lot of user-generated content. Although fair warning, it can look weird on titles and pre-formatted text (

).
  • overflow-wrap
  • hyphens
  • white-space
  • Handling Long Words and URLs

Browser Support

Desktop

Chrome Firefox IE Edge Safari
23 49 11 18 6.1

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
111 110 4.4 7.0-7.1

Safari and iOS support the break-all value but not keep-all

Понравилась статья? Поделить с друзьями:
  • Word break react native
  • Word break not working
  • Word break normal important
  • Word break keep all
  • Word break in english