Do not break word html

say I have a piece of text like this

Hello I am some text Hello I am some
text Hello I am some text Hello I am
some text I do not wish to be broken
on new lines

Consider the above paragraph. I want for the bolded part to not be broken across a new line if possible. As in, I want it to break if it would require a scrollbar or something, but not break if it is possible to insert a page-break before or after that piece of text so that it can fit on one line.

How is this possible? I have tried things like page-break-inside and such, but it doesn’t seem to do anything in firefox.

Justin Ethier's user avatar

Justin Ethier

130k51 gold badges227 silver badges284 bronze badges

asked Mar 1, 2010 at 22:08

Earlz's user avatar

Use the white-space property:

Hello I am some text Hello I am some text Hello I am some text
Hello I am some text <span class="nobr">I do not wish to be
broken on new lines</span>

with:

span.nobr { white-space: nowrap; }

answered Mar 1, 2010 at 22:11

cletus's user avatar

cletuscletus

612k166 gold badges907 silver badges942 bronze badges

4

Adding this for completeness:

If you do not want to use CSS, you could use <nobr>text with space</nobr> — reference here

For pure text blocks, i believe not-anymore-depricated html formatting tags like <i>, <b>, <nobr> and alike are valid for use.
For content relating to the site structure use <em>, <strong> and <span class="">.

answered May 13, 2014 at 14:30

BananaAcid's user avatar

BananaAcidBananaAcid

3,12634 silver badges38 bronze badges

3

answered Jun 29, 2018 at 4:48

Yevgeniy Afanasyev's user avatar

body { word-wrap: break-word;}

I’ve been using that code (above) to fit the text in the body into it’s container. However what I don’t like about it, is that it breaks up words.

Is there another way where it will not break up words and only line break after or before a word?

EDIT: This is for use within a UIWebView.

Abizern's user avatar

Abizern

145k39 gold badges203 silver badges256 bronze badges

asked Sep 23, 2010 at 6:11

Joshua's user avatar

3

use white-space: nowrap;. If you have set width on the element on which you are setting this it should work.

update —
rendered data in Firefox
alt text

Panagiotis Panagi's user avatar

answered Sep 23, 2010 at 8:08

Vinay B R's user avatar

Vinay B RVinay B R

8,0392 gold badges29 silver badges45 bronze badges

9

Please use nowrap and wrap value didn’t come for me. nowrap solved the issue.

white-space: nowrap;

Mechanic's user avatar

Mechanic

4,8574 gold badges15 silver badges36 bronze badges

answered Nov 15, 2017 at 7:19

Code's user avatar

CodeCode

1,5642 gold badges23 silver badges37 bronze badges

1

May be a bit late but you can add this css to stop word breaks:

.element {
    -webkit-hyphens: none;
    -moz-hyphens:    none;
    -ms-hyphens:     none;
    hyphens:         none;
}

answered Jul 27, 2016 at 10:32

Ralphonz's user avatar

RalphonzRalphonz

6231 gold badge9 silver badges22 bronze badges

0

I had the same problem, I solved it using following css:

.className {
  white-space:pre-wrap;
  word-break:break-word;
}

The_Black_Smurf's user avatar

answered Jul 3, 2018 at 17:20

sumit dubey's user avatar

sumit dubeysumit dubey

3472 silver badges5 bronze badges

0

You can try this…

body{
white-space: pre; /* CSS2 */
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP printers */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
word-wrap: break-word; /* IE */
}

{word-wrap:;} is an IE proprietary property, and not a part of css. firefox’s handling is correct. Unfortunately, FF does not support a soft hyphen / . so that’s not an option. You could possibly insert a hair or thin space,  /  (check me on the numeric entity) and  / , respectively.

Making {overflow: hidden;} would cut the overflow off, and {overflow: auto;} would cause the overflow to enable scrolling.

answered Sep 23, 2010 at 6:18

Pramendra Gupta's user avatar

Pramendra GuptaPramendra Gupta

14.5k4 gold badges33 silver badges34 bronze badges

4

For me, the parent was smaller than the word. Adding will break on spaces, but not words :

    word-break: initial;

answered Jul 18, 2020 at 6:38

Andrew Magill's user avatar

Andrew MagillAndrew Magill

2,1664 gold badges20 silver badges28 bronze badges

In my situation I am trying to ensure words wrap at proper word-breaks within table cells.

I found I need the following CSS to achieve this.

table {
  table-layout:fixed;
}
td {
  white-space: wrap;
}

also check that nothing else is changing word-break to break-word instead of normal.

answered Feb 12, 2013 at 23:24

Dave Sag's user avatar

Dave SagDave Sag

13.2k13 gold badges86 silver badges132 bronze badges

0

Use white-space: nowrap;

CSS white-space Property

white-space: normal|nowrap|pre|pre-line|pre-wrap|initial|inherit;

Know more about white-space example

answered Aug 2, 2019 at 4:58

sivahari's user avatar

sivaharisivahari

371 silver badge6 bronze badges

Word break issue on Firefox browser. So you can use to prevent word-break:

-webkit-hyphens: none;
-moz-hyphens: none;
hyphens: none;

tbraun89's user avatar

tbraun89

2,2463 gold badges29 silver badges44 bronze badges

answered Jan 6, 2020 at 10:27

Vaishali Chauhan's user avatar

I use this Code for our website to stop the word-breaking:

body {
    -ms-hyphens: none;
    -webkit-hyphens: none;
    hyphens: none;
}

answered Aug 27, 2020 at 19:08

Web Gemacht's user avatar

To stop words from breaking, you should unset word-break. The default is normal, which allows word breaks but at break points.

overflow-wrap controls when word breaks happen.

You should instead set the overflow-wrap property to always to break words only when they are too long to fit on a line (instead of overflowing).

The default normal to disable word breaks, allowing words too long to overflow the edge of the element.

If your element width is flexible (e.g. min-width, or display:flex), and you want too expand the element instead of line breaking, you can use the value break-word.

The property word-break determines whether words should only break at break points, or always (when they could overflow).

Helpful info and demo on overflow-wrap — MDN Web Docs

Info on word-break

Further things:

  • If you want to disable all word breaks, even when it can’t line break, i.e. japanese text, you can use the word-break: keep-all
  • *The value break-word may have been unsupported and is now deprecated, as is the word-wrap CSS property (initially added by MS for this same function).

answered Jan 24 at 10:24

tutacat's user avatar

I faced a similar problem in my grid structure and I used, word-break: break-word;
in my grid and my issue got resolved.

answered Aug 12, 2016 at 9:06

Abishek's user avatar

2

This helped me with old Webkit — this one from phantomjs 2.1

.table td {
    overflow-wrap: break-spaces;
    word-break: normal;
}

answered Dec 8, 2020 at 11:35

AssyK's user avatar

AssyKAssyK

371 silver badge6 bronze badges

.className {
    hyphens: none;
    word-break: keep-all;
}

answered Jun 6, 2022 at 13:00

Majevski's user avatar

1

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!

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 с нуля

Смотреть

Понравилась статья? Поделить с друзьями:
  • Do loop для excel
  • Do loop vba word
  • Do laptops come with word
  • Do is a general word for actions what are you
  • Do ipads have word on them