Css свойство word-break

How to break long words in an html (or css) table

#2 word-wrap

Lines are wrapped into words in the word-wrap property to fit within the container. Words that aren’t unbreakable can even be broken by this property.

The word-wrap property in CSS breaks long words into lines and wraps them onto the next line. In order to prevent layout problems arising from overflowing text strings, overflow-wrapping is used.

Values

In the property, one of the following values can be specified:

i.) normal

This is the default setting. Regardless of whether a word or an unbroken string overflows the container, the browser will break the line according to the normal line-breaking rules.

ii.) break-word

A line break will be forced at an arbitrary place if the words or strings of characters are too large for their container. By using the hyphens property, a hyphen character will not be rendered.

iii.) inherit

Upon inheriting the overflow-wrap property from its immediate parent, the targeted element must inherit its value.

О запрете переноса слов

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

Для предотвращения разрыва таких слов и символов в тексте можно использовать, например, ссылку на символ («неразрывный пробел»), вставляя её между словами вместо обычного пробела. Такая конструкция будет восприниматься браузером как единое слово и разрываться не будет. Главным недостатком этого способа борьбы за целостность является плохая читабельность исходного текста документа. В таком сплошном тексте очень сложно ориентироваться при редактировании.

Пример организации неразрывного текста с помощью «неразрывного пробела»:

<p>Тургенев&nbsp;И.С.&nbsp;&mdash; русский писатель
   второй половины XIX&nbsp;века.</p>

До недавнего времени некоторые веб-разработчики для формирования неразрывных строк использовали также нестандартный парный тег (сокр. от англ. no-break — «без разрыва»). Текст, помещённый внутрь такого элемента, становится неразрывным и выводится в одной строке. В случае если данная строка не убирается на экране, в нижней части окна браузера появляются горизонтальные полосы прокрутки.

Пример использования тега :

<p><nobr>Lorem ipsum dolor sit amet, consectetuer
adipiscing elit, sed diem nonummy nibh euismod
tincidunt ut lacreet dolore magna aliguam erat
volutpat.</nobr> Ut wisis enim ad minim veniam,
quis nostrud exerci tution ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo
consequat.</p>

Результат в браузере:

Элемент изначально поддерживается всеми браузерами, но не вошёл ни в одну из спецификаций HTML, а потому исходный код с использованием данного элемента не пройдёт проверку на валидаторе. Вместо него рекомендуется использовать средства CSS. Аналогом в CSS является свойство .

С использованием средств CSS вышеприведённый пример будет выглядеть следующим образом:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <style>
      .nbr {white-space: nowrap;}
   </style>
</head>

<body>
   <p><span class="nbr">Lorem ipsum dolor sit
   amet, consectetuer adipiscing elit, sed diem
   nonummy nibh euismod tincidunt ut lacreet
   dolore magna aliguam erat volutpat.</span>
   Ut wisis enim ad minim veniam, quis nostrud
   exerci tution ullamcorper suscipit lobortis
   nisl ut aliquip ex ea commodo consequat.</p>
</body>
</html>

Примечание: Внутри неразрывных строк, созданных с помощью элемента или средств CSS, явный перенос не выполняется и ссылка на символ («место возможного переноса») игнорируется. Для указания места, где возможен перенос в такой строке, следует использовать тег .

Другие статьи по схожей тематике

  • Об использовании кавычек и тире в текстовом содержимом элементов
  • Ссылки на символы
  • Список наиболее часто используемых ссылок на символы
  • Списки на веб-страницах
  • Оформление цитат на веб-странице
  • Стилизация текста средствами CSS

Автоматический перенос строк в браузере

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

Если же на странице не убирается сложное слово, состоящее из двух слов, записанных через дефис (например, слово «блекло-голубой»), и первое слово с дефисом при этом убираются на странице, то перенос происходит после дефиса. То есть переносится только вторая часть слова (в нашем примере — слово «голубой»).

Make breaks more elegant using CSS hyphens

property allows text to be hyphenated when words are too long to fit in one line. Hyphenation opportunities depend on the language of your content.

Native support is at the moment. Worst thing is is not working at all in Windows Chrome (it does work on Android and Mac OS plateforms). Proprietary prefixes and one of the fix ( or ) as a complement are necessary to make this solution viable.

Since hyphenation rules are language-specific, you also need the attribute to be defined on a parent element (mostly on the tag).

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lobortis dui. Duis tempor ligula scelerisque sodales faucibus. Quisque sodales leo nec. loremipsumdolorsitametconsectetur

Значение свойств

Значение Описание
normal Значение по умолчанию. Использует правила разрыва строки по умолчанию
break-all Чтобы предотвратить переполнение, слово может быть разбито на любой символ
keep-all  Разрывы слов не должны использоваться для китайского/японского/корейского текста (CJK). Не иероглифическом тексте поведение такое же, как значение «normal»
break-word Чтобы предотвратить переполнение, слово может быть разбито в произвольных точках
initial Устанавливает для этого свойства значение по умолчанию. Прочитайте о initial
inherit Наследует это свойство от родительского элемента. Прочитайте о inherit

The hard‐coded way: Markup

There are 2 different ways to break words by modifing the markup structure:

  1. Using the
  2. Using the

The <wbr> element

The element breaks the word in the position that is inserted only when the content does not fit the container, without showing any additional character. In fact, the element is never visible in any case, behaving very similar with the “zero‐width space” () unicode character.

The element is usefull for some cases, such as for CJK (Chinese, Japanese, and Korean) languages, when we need to control and introduce an optional word/line break, while we disallow the line breaks in any other part of the text.

The soft hyphen character

The character breaks the word and renders a hyphen character, only when the content does not fit the container.

While the character is a useful solution for most western languages, it is not a very useful solution for CJK languages, since the hyphen character does not exist as a word breaking option.

On the other hand, modern browsers have hyphenation capabilities through the CSS property, but this property works only for the supported languages. For example Firefox does not support the Greek language for hyphenation — while Safari does support Greek. With the character we can simulate a hyphenated text even for non‐supported languages and on all browsers.

Example Code

Working Example within an HTML Document

<!DOCTYPE html>
<title>Example</title>
<style>
div {
width: 6em;
background: beige;
margin-right: 1em;
float: left;
}
.word-break {
word-break: break-all;
}
.word-wrap {
word-wrap: break-word;
}
</style>
<div>
<strong>Normal:</strong>
<p>Collaboratively administrate empowered markets via plug-and-play networks.</p>
<p>Efficiently unleash cross-media information without cross-media value.</p>
</div>
<div class=»word-break»>
<strong>word-break:</strong>
<p>Collaboratively administrate empowered markets via plug-and-play networks.</p>
<p>Efficiently unleash cross-media information without cross-media value.</p>
</div>
<div class=»word-wrap»>
<strong>word-wrap:</strong>
<p>Collaboratively administrate empowered markets via plug-and-play networks.</p>
<p>Efficiently unleash cross-media information without cross-media value.</p>
</div>

Reproducible Example:

Below is the source HTML for the above examples:

overflow-wrap HTML + CSS Sample

<!DOCTYPE html>
<html lang="en">
    <style>
        .body {
            font-size: 12;
        }

        p {
           width: 400px;
           margin: 2px;
            border: 1px solid red;
        }

        .ow-anywhere {
           overflow-wrap: anywhere;
        }

        .ow-break-word {
           overflow-wrap: break-word;
        }

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

        .hyphens {
           hyphens: auto;
        }

        .wrap-anywhere {
            width: 30px;
        }

    </style>

    <head>
        <meta charset="utf-8">
        <title>Title</title>
    </head>

    <body>

        <p class="label">1.  <i>overflow-wrap: normal;</i></p>
        <p>I frolick happily down by the sea shore.
            I <i class="normal">Supercalifragilisticexpialidociouslydociouslydociouslydociouslydociously</i>,
            think my crabs are over-cooked.</p>
        <br>

        <p class="label">2.  <i>overflow-wrap: break-word;</i></p>
        <p>I frolick happily down by the sea shore.
            I <i class="ow-break-word">Supercalifragilisticexpialidociouslydociouslydociouslydociouslydociously</i>,
            think my crabs are over-cooked.</p>
        <br>

        <p class="label">3.  <i>overflow-wrap: anywhere;</i></p>
        <p class="wrap-anywhere ow-anywhere">I frolick happily down by the sea shore.
            I
            think my crabs are overcooked.</p>
        <br>

        <p class="label">4.  <i>overflow-wrap: break-all;</i></p>
        <p>I frolick happily down by the sea shore.
            I <i class="word-break">Supercalifragilisticexpialidociouslydociouslydociouslydociouslydociously</i>,
            think my crabs are over-cooked.</p>
        <br>

        <p class="label">5.  <i>overflow-wrap: hyphens;</i></p>
        <p>I frolick happily down by the sea shore.
            I <i class="hyphens">Supercalifragilisticexpialidociouslydociouslydociouslydociouslydociously</i>,
            think my crabs are over-cooked.</p>
        <br>
    </body>
</html>

The following is the code snippet for converting the above HTML snippet to PDF:

Below is our resultant PDF document:

CSS Справочники

CSS СправочникCSS ПоддержкаCSS СелекторыCSS ФункцииCSS ЗвукCSS Веб шрифтыCSS АнимацииCSS ДлиныCSS Конвертер px-emCSS Названия цветаCSS Значения цветаCSS по умолчаниюCSS Символы

CSS Свойства

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
caption-side
caret-color
@charset
clear
clip
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
writing-mode
z-index

How to use line breaking

Line breaking in Webflow (known as the “white-space” property in CSS) controls how whitespace characters (i.e., characters which represent horizontal or vertical space between other characters) and newline characters (i.e., whitespace characters which represent a line break) are handled, and whether text wraps or overflows. 

There are 6 options for line breaking: 

  • Normal — default value which collapses sequences of whitespace (i.e., compresses sequences of multiple whitespace characters down to a single space character) and wraps text to the next line as needed
  • No wrap — collapses sequences of whitespace the same as Normal, but keeps text on a single line without wrapping, even if the text overflows
  • Pre — preserves sequences of whitespace and line breaks and keeps text exactly as it appears in the HTML source code
  • Pre wrap — preserves sequences of whitespace and allows text to wrap to the next line as needed
  • Pre line — collapses sequences of white space (i.e., compresses sequences of multiple whitespace characters down to a single space character), preserves line breaks, and allows text to wrap to the next line as needed
  • Spaces — preserves sequences of whitespace, allows text to wrap at any point as needed, and doesn’t remove trailing spaces 
Pro tip: You can learn more about the white-space property and preview these options in the MDN web docs.

How to set line breaks 

Before you can set line breaks, you’ll need to add a text element (e.g., rich text, paragraph, etc.) to the canvas. 

To set line breaks: 

  1. Select the text element on the canvas
  2. Go to Style panel > Typography > More type options > Breaking
  3. Select a line break option from the Line dropdown (i.e., Normal, No wrap, Pre, Pre wrap, Pre line, or Spaces) 

As with other style properties, you can add line breaks to a parent element or breakpoint and override it on child elements or lower or higher breakpoints. 

How to use word breaking

With word breaking (the “word-break” CSS property), you can change the default line breaking behavior and specify where line breaks appear in text that would otherwise overflow. You can use word breaks to avoid awkward line breaks for content with compound words, or to adhere to language-specific rules and ensure a proper display for a better international user experience. 

There are 3 options for word breaking: 

  • Normal — default value which uses the default rules for word breaking (i.e., breaking at spaces or hyphens)
  • Break all — to prevent overflow, any word or character can break onto the next line (excluding Chinese/Japanese/Korean text)
  • Keep all — for Chinese, Japanese, and Korean (CJK) text, words are not broken even if there is content overflow. Non-CJK text behavior is the same as Normal 
Pro tip: You can learn more about the word-break property and preview these options in the MDN web docs.

How to set word breaks

Before you can set word breaks, you’ll need to add a text element (e.g., rich text, paragraph, etc.) to the canvas. 

To set word breaks: 

  1. Select the text element on the canvas
  2. Go to Style panel > Typography > More type options > Breaking
  3. Select a word break option from the Word dropdown (i.e., Normal, Break all, or Keep all) 

As with other style properties, you can add word breaks to a parent element or breakpoint and override it on child elements or on lower or higher breakpoints. 

Line height

Change the line height with utilities.

Some placeholder content to show off the line height utilities. Happy birthday. You could’ve been the greatest. She ride me like a roller coaster. I messed around and got addicted. You just gotta ignite the light and let it shine! I’m intrigued, for a peek, heard it’s fascinating. Catch her if you can. I should’ve told you what you meant to me ‘Cause now I pay the price. Do you ever feel, feel so paper thin.

But you better choose carefully. Yo, shout out to all you kids, buying bottle service, with your rent money. She’s sweet as pie but if you break her heart. Just own the night like the 4th of July! In another life I would be your girl. Playing ping pong all night long, everything’s all neon and hazy. Shorty so bad, I’m sprung and I don’t care.

I can feel a phoenix inside of me. Maybe a reason why all the doors are closed. We go higher and higher. Passport stamps, she’s cosmopolitan. Someone said you had your tattoo removed. All my girls vintage Chanel baby. Someone said you had your tattoo removed.

But I will get there. This is real so take a chance and don’t ever look back, don’t ever look back. You could travel the world but nothing comes close to the golden coast. Of anything and everything. Venice beach and Palm Springs, summertime is everything. Do you ever feel already buried deep six feet under? It’s time to bring out the big balloons. So cover your eyes, I have a surprise. So I don’t have to say you were the one that got away.

Instructions

Use Word and Line Break Information

Word-break procedures for rich edit controls are similar to those for edit controls, but they have additional capabilities: word-break procedures for both kinds of controls can determine whether a character is a delimiter and can find the nearest word break before or after the specified position. A delimiter is a character that marks the end of a word, such as a space. Usually, in an edit control, a word break occurs only after delimiters. However, different rules apply to most Asian languages.

Word-break procedures for rich edit controls also group characters into character classes, each identified by a value in the range 0x00 through 0x0F. Breaks occur either after delimiters or between characters of different classes. Thus, a word-break procedure with different classes for alphanumeric and punctuation characters would find two word breaks in the string «Win.doc» (before and after the period).

A character’s class can be combined with zero or more word-break flags to form an 8-bit value. When performing word-wrap operations, a rich edit control uses word-break flags to determine where it can break lines. Rich Edit uses the following word-break flags.

Flag Description
WBF_BREAKAFTER Lines may be broken after the character.
WBF_BREAKLINE The character is a delimiter. Delimiters mark the ends of words. Lines may be broken after delimiters.
WBF_ISWHITE The character is a white-space character. Trailing white-space characters are not included in the length of a line when wrapping.

The WBF_BREAKAFTER value is used to allow wrapping after a character that does not mark the end of a word, such as a hyphen.

You can replace the default word-break procedure for a rich edit control with your own procedure by using the EM_SETWORDBREAKPROC message. For more information about word-break procedures, see the description of the EditWordBreakProc function.

Note

This replacement is not recommended for Microsoft Rich Edit 2.0 and later, due to the complexity of multilingual word breaking.

For Microsoft Rich Edit 1.0, you can use the EM_SETWORDBREAKPROCEX message to replace the default extended word-break procedure with an EditWordBreakProcEx function. This function provides additional information about the text, such as the character set. You can use the EM_GETWORDBREAKPROCEX message to retrieve the address of the current extended word-break procedure. Note that Microsoft Rich Edit 2.0 and later do not support EditWordBreakProcEx, EM_GETWORDBREAKPROCEX, and EM_SETWORDBREAKPROCEX.

You can use the EM_FINDWORDBREAK message to find word breaks or to determine a character’s class and word-break flags. In turn, the control calls its word-break procedure to get the requested information.

To determine which line a given character falls on, you can use the EM_EXLINEFROMCHAR message.

Browser compatibility

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome
Full support

1
Edge
Full support

12
Firefox
Full support

15
IE
Full support

5.5
Notes
Opera
Full support

15
Safari
Full support

3
WebView Android
Full support

≤37
Chrome Android
Full support

18
Firefox Android
Full support

15
Opera Android
Full support

14
Safari iOS
Full support

2
Samsung Internet Android
Full support

1.0
Chrome
Full support

1
Edge
Full support

79
Firefox
Full support

67
IE
No support

No
Opera
Full support

15
Safari
Full support

3
WebView Android
Full support

≤37
Chrome Android
Full support

18
Firefox Android
Full support

67
Opera Android
Full support

14
Safari iOS
Full support

2
Samsung Internet Android
Full support

1.0
Chrome
Full support

44
Edge
Full support

12
Firefox
Full support

15
IE
Full support

5.5
Opera
Full support

31
Safari
Full support

9
WebView Android
Full support

44
Chrome Android
Full support

44
Firefox Android
Full support

15
Opera Android
Full support

32
Safari iOS
Full support

9
Samsung Internet Android
Full support

4.0

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: unset;

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

Values

Use the default line break rule.
To prevent overflow, word breaks should be inserted between any two characters (excluding Chinese/Japanese/Korean text).
Word breaks should not be used for Chinese/Japanese/Korean (CJK) text. Non-CJK text behavior is the same as for .
Has the same effect as and , regardless of the actual value of the property.

Note: In contrast to and (see ), 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).

How to use text wrapping

Wrapping (the “overflow-wrap” CSS property) lets you control how words wrap when they exceed the width of their parent element. This ensures that words break at the nearest opportunity within the container, maintaining the integrity and aesthetic of your design. 

There are 3 options for wrapping: 

  • Normal — default value which uses the default rules for breaking (i.e., breaking at spaces between words or hyphens)
  • Anywhere — to prevent overflow, an otherwise unbreakable string of characters (e.g., a URL or a long word) may be broken at any point if there are no otherwise acceptable break points in the line
  • Break word — behaves the same as the Anywhere option, where normally unbreakable words can be broken at arbitrary points if there are no otherwise acceptable break points in the line
Pro tip: You can learn more about the overflow-wrap property and preview these options in the MDN web docs.

How to set wrapping behavior

Before you can set wrapping behavior, you’ll need to add a text element (e.g., rich text, paragraph, etc.) to the canvas. 

To set wrapping behavior: 

  1. Select the text element on the canvas
  2. Go to Style panel > Typography > More type options > Wrap
  3. Select a wrap option (i.e., Normal, Anywhere, or Break word)

As with other style properties, you can add wrapping to a parent element or breakpoint and override it on child elements or lower or higher breakpoints. 

Понравилась статья? Поделиться с друзьями:
Setup Pro
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: