Allows lines to be broken within words if an otherwise unbreakable string is too long to fit. Currently mostly supported using the word-wrap
property.
Chrome
- 4 — 22: Partial support
- 23 — 111: Supported
- 112: Supported
- 113 — 115: Supported
Edge
- 12 — 17: Partial support
- 18 — 110: Supported
- 111: Supported
Safari
- 3.1 — 6: Partial support
- 6.1 — 16.3: Supported
- 16.4: Supported
- 16.5 — TP: Supported
Firefox
- 2 — 3: Not supported
- 3.5 — 48: Partial support
- 49 — 110: Supported
- 111: Supported
- 112 — 113: Supported
Opera
- 9 — 10.1: Not supported
- 10.5 — 12: Partial support
- 12.1 — 94: Supported
- 95: Supported
IE
- 5.5 — 10: Partial support
- 11: Partial support
Chrome for Android
- 111: Supported
Safari on iOS
- 3.2 — 6.1: Partial support
- 7 — 16.3: Supported
- 16.4: Supported
- 16.5: Supported
Samsung Internet
- 4 — 19.0: Supported
- 20: Supported
Opera Mini
- all: Partial support
Opera Mobile
- 10 — 12.1: Partial support
- 73: Supported
UC Browser for Android
- 13.4: Supported
Android Browser
- 2.1 — 4.3: Partial support
- 4.4 — 4.4.4: Supported
- 111: Supported
Firefox for Android
- 110: Supported
QQ Browser
- 13.1: Supported
Baidu Browser
- 13.18: Supported
KaiOS Browser
- 2.5: Partial support
- 3: Supported
Partial support refers to requiring the legacy name «word-wrap» (rather than «overflow-wrap») to work.
- Resources:
- Bug on Firefox support
- MDN Web Docs — CSS overflow-wrap
- WebPlatform Docs
Allows lines to be broken within words if an otherwise unbreakable string is too long to fit. Currently mostly supported using the word-wrap
property.
What browser do support wordwrap widget
Add this code to your website
<script data-feature=»wordwrap» defer src=»https://cdn.caniusewidgets.com/scripts/overviewtable.js»></script>
to display the following widget
⇓
How many browsers globally do support wordwrap widget
Add this code to your website
<script data-feature=»wordwrap» defer src=»https://cdn.caniusewidgets.com/scripts/browsersupport.js»></script>
to display the following widget
⇓
Is wordwrap supported in my browser widget
Add this code to your website
<script data-feature=»wordwrap» defer src=»https://cdn.caniusewidgets.com/scripts/single.js»></script>
to display the following widget
⇓
caniusewidgets.com/wordwrap
Change caniuse.com to
caniusewidgets.com to
get to this page
How can text like aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
which exceeds the width of a div
(say 200px
) be wrapped?
I am open to any kind of solution such as CSS, jQuery, etc.
trejder
17k27 gold badges123 silver badges215 bronze badges
asked Jul 18, 2009 at 15:56
Satya KalluriSatya Kalluri
5,1084 gold badges27 silver badges37 bronze badges
Try this:
div {
width: 200px;
word-wrap: break-word;
}
answered Jul 18, 2009 at 16:02
Alan Haggai AlaviAlan Haggai Alavi
72.2k19 gold badges101 silver badges127 bronze badges
6
On bootstrap 3, make sure the white-space is not set as ‘nowrap’.
div {
width: 200px;
word-break: break-all;
white-space: normal;
}
answered Nov 12, 2013 at 8:39
2
You can use a soft hyphen like so:
aaaaaaaaaaaaaaa­aaaaaaaaaaaaaaa
This will appear as
aaaaaaaaaaaaaaa-
aaaaaaaaaaaaaaa
if the containing box isn’t big enough, or as
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
if it is.
Tunaki
131k46 gold badges330 silver badges415 bronze badges
answered Jul 18, 2009 at 16:13
Kim StebelKim Stebel
41.6k12 gold badges125 silver badges142 bronze badges
7
div {
/* Set a width for element */
word-wrap: break-word
}
The ‘word-wrap
‘ solution only works in IE and browsers supporting CSS3
.
The best cross browser solution is to use your server side language (php or whatever) to locate long strings and place inside them in regular intervals the html entity
This entity breaks the long words nicely, and works on all browsers.
e.g.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
code
5,1204 gold badges16 silver badges37 bronze badges
answered Jul 18, 2009 at 16:14
Orr SiloniOrr Siloni
1,24010 silver badges20 bronze badges
1
This worked for me
word-wrap: normal;
word-break: break-all;
white-space: normal;
display: block;
height: auto;
margin: 3px auto;
line-height: 1.4;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
answered Jun 2, 2016 at 2:04
AmolAmol
9087 silver badges20 bronze badges
1
The only one that works across IE, Firefox, chrome, safari and opera if there are no spaces in the word (such as a long URL) is:
div{
width: 200px;
word-break: break-all;
}
I found this to be bullet-proof.
answered Apr 12, 2013 at 13:56
Kyle DearleKyle Dearle
1291 gold badge2 silver badges9 bronze badges
0
Another option is also using:
div
{
white-space: pre-line;
}
This will set all your div elements in all browsers that support CSS1 (which is pretty much all common browsers as far back as IE
answered Oct 14, 2014 at 15:59
1
Cross Browser
.wrap
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
answered Apr 20, 2015 at 9:21
TimelessTimeless
7,2898 gold badges60 silver badges94 bronze badges
<p style="word-wrap: break-word; word-break: break-all;">
Adsdbjf bfsi hisfsifisfsifs shifhsifsifhis aifoweooweoweweof
</p>
answered Oct 1, 2020 at 20:23
Manoj AlwisManoj Alwis
1,27911 silver badges24 bronze badges
Example from CSS Tricks:
div {
-ms-word-break: break-all;
/* Be VERY careful with this, breaks normal words wh_erever */
word-break: break-all;
/* Non standard for webkit */
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}
More examples here.
answered Feb 4, 2015 at 10:01
In HTML body try:
<table>
<tr>
<td>
<div style="word-wrap: break-word; width: 800px">
Hello world, how are you? More text here to see if it wraps after a long while of writing and it does on Firefox but I have not tested it on Chrome yet. It also works wonders if you have a medium to long paragraph. Just avoid writing in the CSS file that the words have to break-all, that's a small tip.
</div>
</td>
</tr>
</table>
In CSS body try:
background-size: auto;
table-layout: fixed;
John Slegers
44.5k22 gold badges201 silver badges169 bronze badges
answered Feb 6, 2016 at 17:06
Add this CSS to the paragraph.
width:420px;
min-height:15px;
height:auto!important;
color:#666;
padding: 1%;
font-size: 14px;
font-weight: normal;
word-wrap: break-word;
text-align: left;
TylerH
20.6k64 gold badges76 silver badges97 bronze badges
answered May 23, 2012 at 9:53
Swapnil GodambeSwapnil Godambe
2,0541 gold badge24 silver badges28 bronze badges
1
Try this
div{
display: block;
display: -webkit-box;
height: 20px;
margin: 3px auto;
font-size: 14px;
line-height: 1.4;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
the property text-overflow: ellipsis add … and line-clamp show the number of lines.
answered Nov 27, 2014 at 21:10
I have used bootstrap.
My html code looks like ..
<div class="container mt-3" style="width: 100%;">
<div class="row">
<div class="col-sm-12 wrap-text">
<h6>
text content
</h6>
</div>
</div>
</div>
CSS
.wrap-text {
text-align:justify;
}
Stephen Rauch♦
47.2k31 gold badges110 silver badges133 bronze badges
answered Sep 18, 2018 at 2:24
1
you can use this CSS
p {
width: min-content;
min-width: 100%;
}
answered Dec 27, 2019 at 10:22
Rashid IqbalRashid Iqbal
1,05313 silver badges12 bronze badges
Try this CSS property —
overflow-wrap: anywhere;
answered Jun 9, 2022 at 6:12
A server side solution that works for me is: $message = wordwrap($message, 50, "<br>", true);
where $message
is a string variable containing the word/chars to be broken up. 50 is the max length of any given segment, and "<br>"
is the text you want to be inserted every (50) chars.
answered Jan 23, 2012 at 7:31
1
Try this
div {display: inline;}
answered Jul 18, 2018 at 16:58
try:
overflow-wrap: break-word;
borchvm
3,48411 gold badges45 silver badges43 bronze badges
answered Jan 29, 2020 at 3:00
Use word-wrap:break-word
attribute along with required width. Mainly, put
the width in pixels, not in percentages.
width: 200px;
word-wrap: break-word;
JSuar
21.1k4 gold badges43 silver badges82 bronze badges
answered Jan 27, 2011 at 8:36
1
Editor’s note: This complete guide to word-wrap
, overflow-wrap
, and word-break
in CSS was last updated 24 February 2023 to reflect the reflect the most recent version of CSS, include interactive code examples, and include a section on how to wrap text using CSS. To learn more about the overflow
property, check out our guide to CSS overflow
.
Making a site responsive so that it displays correctly on all devices is very important in this day and age. Unfortunately, despite your best efforts to do so, you may still end up with broken layouts. Broken layouts can happen when certain words are too long to fit in their container. Content overflow can occur when you are dealing with user-generated content you have no control over, such as the comments section of a post. Therefore, you need to apply styling to prevent content from overflowing their container.
Content overflow is a common problem for frontend developers. On the web, overflow occurs when your content doesn’t fit entirely within its containing element. As a result, it spills outside. In CSS, you can manage content overflow mainly using the overflow
, word-wrap
, overflow-wrap
, and word-break
CSS properties. However, our focus in this article will be on the word-wrap
, overflow-wrap
, and word-break
CSS properties.
Jump ahead:
- Using
word-wrap
,overflow-wrap
, andword-break
CSS properties- How does content wrapping occur in browsers?
- What is the difference between a soft wrap break and a forced line break?
- Understanding the
Word-wrap
andoverflow-wrap
CSS propertiesNormal
Anywhere
Break-word
- Implementing the
Word-break
CSS property- Setting
word-break
toNormal
- The
Break-all
value - Using the
Keep-all
value
- Setting
- What is the difference between
overflow-wrap
andword-break
? - How to wrap text using CSS
- Troubleshooting CSS content overflow with Chrome DevTools
Using word-wrap
, overflow-wrap
, and word-break
CSS properties
You can use the word-wrap
, overflow-wrap
, or word-break
CSS properties to wrap or break words that would otherwise overflow their container. This article is an in-depth tutorial on the word-wrap
, overflow-wrap
, and word-break
CSS properties and how you can use them to prevent content overflow from ruining your nicely styled layout. Before we get started, let us understand how browsers wrap content in the next section.
How does content wrapping occur in browsers?
Browsers and other user agents perform content wrapping at allowed breakpoints, referred to as soft wrap opportunities. A browser will wrap content at a soft wrap opportunity, if one exists, to minimize content overflow. In English and other similar writing systems, soft wrap opportunities occur by default at word boundaries in the absence of hyphenation. Because words are bound by spaces and punctuation, that is where soft wraps occur.
Although soft wraps occur in space characters in English texts, the situation might be different for non-English writing systems. Some languages do not use spaces to separate words, meaning that content wrapping depends on the language or writing system. The value of the lang
attribute you specify on the HTML
element is mostly used to determine which language system is used.
This article will focus mainly on the English language writing system. The default wrapping at soft wrap opportunities may not be sufficient if you are dealing with long, continuous text, such as URLs or user-generated content, which you have very little or no control over. Before we go into a detailed explanation of these CSS properties, let’s look at the differences between soft wrap break and forced line break in the section below.
What is the difference between a soft wrap break and a forced line break?
Any text wrap that occurs at a soft wrap opportunity is referred to as a soft wrap break. For wrapping to occur at a soft wrap opportunity, you need to make sure you’ve enabled wrapping. For example, setting the value of white-space
CSS property to nowrap
will disable wrapping. Forced line breaks are caused by explicit line-breaking controls or line breaks marking the end or start of blocks of text.
Understanding the Word-wrap
and overflow-wrap
CSS properties
The name word-wrap
is the legacy name for the overflow-wrap
CSS property. Word-wrap
was originally a non-prefixed Microsoft extension and was not part of the CSS standard, though most browsers implemented it with the name word-wrap
. According to the draft CSS3 specification, browsers should treat word-wrap
as a legacy name alias of the overflow-wrap
property for compatibility.
Most recent versions of popular web browsers have implemented the overflow-wrap
property. The draft CSS3 specification refers to the overflow-wrap
property as:
This property specifies whether the browser may break at otherwise disallowed points within a line to prevent overflow when an otherwise-unbreakable string is too long to fit within the line box.
If you have a white-space
property on an element, you need to set its value to allow wrapping for overflow-wrap
to have an effect. Below are the values of the overflow-wrap
property:
overflow-wrap: normal; overflow-wrap: anywhere; overflow-wrap: break-word;
You can also use the global values inherit
, initial
, revert
, and unset
with overflow-wrap
, but we won’t cover them here. In the subsections below, we will look at the values of the overflow-wrap
CSS property outlined above to understand the behavior of this property.
Normal
Applying the value normal
will make the browser use the default line-breaking behavior of the system. For English and other related writing systems, line breaks will therefore occur at whitespaces and hyphens, as shown below:
.my-element{ overflow-wrap: normal; }
In the example below, there is a word in the text that is longer than its container. Because there is no soft wrap opportunity and the value of the overflow-wrap
property is normal
, the word overflows its container. It describes the default line-breaking behavior of the system:
See the Pen
overflow-wrap-normal by Joseph Mawa (@nibble0101)
on CodePen.
Anywhere
Using the value anywhere
will break an otherwise unbreakable string at arbitrary points between two characters. It will not insert a hyphen character even if you apply the hyphens
property on the same element.
The browser will break the word only if displaying the word on its line will cause an overflow. If the word still overflows when placed on its line, it will break the word at the point where an overflow would otherwise occur. When you use anywhere
, the browser will consider the soft wrap opportunities introduced by the word break when calculating min-content
intrinsic sizes:
.my-element{ overflow-wrap: anywhere; }
Unlike in the previous section, where we used overflow-wrap: normal
, in the example below, we are using overflow-wrap: anywhere
. The overflowing word that is otherwise unbreakable is broken into chunks of text using overflow-wrap: anywhere
so that it fits in its container:
See the Pen
overlow-wrap-anywhere by Joseph Mawa (@nibble0101)
on CodePen.
Most recent versions of desktop browsers support overflow-wrap:
anywhere
. However, support for some mobile browsers is either lacking or unknown. The image below shows the browser support:
Break-word
The value break-word
is like anywhere
in terms of functionality. If the browser can wrap the overflowing word to its line without overflowing, that is what it will do. However, if the word still overflows its container even when it is on its line, the browser will break it at the point where the overflow would otherwise occur:
.my-element{ overflow-wrap: break-word; }
The example below shows how the browser breaks the overflowing text when you apply overflow-wrap: break-word
:
See the Pen
overflow-wrap-break-word by Joseph Mawa (@nibble0101)
on CodePen.
Notice that the text appears the same as in the last subsection. The difference between overflow-wrap: anywhere
and overflow-wrap: break-word
is in the min-content
intrinsic sizes.
The difference between anywhere
and break-word
is apparent when calculating the min-content
intrinsic sizes. With break-word
, the browser doesn’t consider the soft wrap opportunities introduced by the word break when calculating min-content
intrinsic sizes, but it does with anywhere
. For more about min-content
intrinsic sizes, check out our guide here.
The value break-word
has decent coverage among the most recent versions of desktop browsers. Unfortunately, you cannot say the same about their mobile counterpart. It is, therefore, safer to use the legacy word-wrap: break-word
instead of the more recent overflow-wrap: break-word
.
The image below shows browser support for overflow-wrap: break-word
:
The most recent versions of desktop browsers have support, while support for some mobile browsers is unknown.
Implementing the Word-break
CSS property
Word-break
is another CSS property you can use to specify soft wrap opportunities between characters. You can use this property to break a word at the exact spot where an overflow would occur and wrap it onto the following line.
The draft CSS3 specification refers to the word-break
CSS property as:
This property specifies soft wrap opportunities between letters, i.e., where it is “normal” and permissible to break lines of text. It controls what types of letters the browser can glom together to form unbreakable “words” — causing CJK characters to behave like non-CJK text or vice versa.
Below are the possible values of the word-break
CSS property. Like overflow-wrap
, you can use the global values inherit
, initial
, revert
, and unset
with word-break
, but we won’t cover them here:
word-break: normal; word-break: break-all; word-break: keep-all;
Break-word
is also a value of the word-break
CSS property, though it was removed. However, browsers still support it for legacy reasons. Specifying this property has the same effect as word-break: normal
and overflow-wrap: anywhere
.
Now that we know the break-word
CSS property and its corresponding values, let us look at them in the subsections below.
Setting word-break
to Normal
Setting the value of the word-break
property to normal
will apply the default word breaking rules:
.my-element{ word-break: normal; }
The example below illustrates what happens when you apply the styling word-break: normal
to a block of text that contains a word longer than its container:
See the Pen
word-break-normal by Joseph Mawa (@nibble0101)
on CodePen.
What you see is the browser’s usual word-breaking rules in effect.
The Break-all
value
The value break-all
will insert a line break at the exact point where the text would otherwise overflow for non-Chinese, non-Japanese, and non-Korean writing systems. It will not put the word on its own line, even if doing so will prevent the need to insert a line break:
.my-element{ word-break: break-all; }
In the example below, I am applying word-break: break-all
styling to a p
element of width 240px
containing an overflowing text. The browser will insert a line break at the point where an overflow would occur and wrap the remaining text to the following line:
See the Pen
word-break-break-all by Joseph Mawa (@nibble0101)
on CodePen.
Using break-all
will break a word between two characters at the exact point where an overflow would occur in English and other related language systems. However, it won’t apply the same behavior to Chinese, Japanese, and Korean (CJK) texts.
It doesn’t apply the same behavior for CJK texts because CJK writing systems have their own rules for applying breakpoints. Creating a line break between two characters arbitrarily just for the sake of avoiding overflow might significantly change the overall meaning of the text. For CJK systems, the browser will apply line breaks at the point where such breaks are allowed.
Using the Keep-all
value
If you use the value keep-all
, the browser will not apply word breaks to CJK texts, even if there is content overflow. The effect of applying keep-all
value is the same as that of normal
for non-CJK writing systems:
.my-element{ word-break: keep-all; }
In the example below, applying word-break: keep-all
will have the same effect as word-break: normal
for a non-CJK writing system such as English:
See the Pen
word-break-keep-all by Joseph Mawa (@nibble0101)
on CodePen.
The image below shows the browser support for word-break: keep-all
:
This value has support in most popular desktop browsers. Unfortunately, it is not the case for mobile browsers. Now that we have looked at the overflow-wrap
and word-break
CSS properties, what is the difference between the two? The section below will shed light on that.
What is the difference between overflow-wrap
and word-break
?
You can use the CSS properties overflow-wrap
and word-break
to manage content overflow. However, there are differences in the way the two properties handle it.
Using overflow-wrap
will wrap the entire overflowing word to its line if it can fit in a single line without overflowing its container. The browser will break the word only if it cannot place it on a new line without overflowing. In most cases, the overflow-wrap
property or its legacy name word-wrap
might manage content overflow. Using word-wrap: break-word
will wrap the overflowing word onto a new line and goes ahead to break it between two characters if it still overflows its container.
Word-break
will ruthlessly break the overflowing word between two characters even if placing it on its line will negate the need for word break. Some writing systems, like the CJK writing systems, have strict word breaking rules the browser takes into consideration when creating line breaks using word-break
.
How to wrap text using CSS
As hinted above, if you want to wrap text or break a word overflowing the confines of its box, your best bet is the overflow-wrap
CSS property. You can also use its legacy name, word-wrap
. Try the word-break
CSS property if the overflow-wrap
property doesn’t work for you. However, be aware of the differences between overflow-wrap
and word-break
highlighted above.
Below is an illustration of the overflow-wrap
and word-wrap
CSS properties. You can play with the CodePen to understand their effects:
See the Pen
how-to-wrap-text by Joseph Mawa (@nibble0101)
on CodePen.
Troubleshooting CSS content overflow with Chrome DevTools
More often than not, you might need to fix broken layouts caused by content overflow, as complex user interfaces are now commonplace in frontend development. Modern web browsers come with tools for troubleshooting such layout issues, such as Chrome DevTools.
It provides the capability to select an element in the DOM tree so that you can view, add, and remove CSS declarations and much more. It will help you track down the offending CSS style in your layout and fix it with ease.
To open the Chrome DevTools, you can use the F12
key. When open, it looks like in the image below. Selecting an element in the DOM tree will display its corresponding CSS styles. You can modify the styles and see the effect on your layout as you track down the source of the bug:
As already mentioned, if you have white-space
property on an element, set its value to allow wrapping for overflow-wrap: anywhere
or overflow-wrap: break-word
to work.
Setting the value of overflow-wrap
property to anywhere
or break-word
on a table
content won’t break an overflowing word like in the examples above. The table will overflow its container and create a horizontal scroll if necessary. To get the table to fit within its container and overflow-wrap
to work, set the value of the table-layout
property to fixed
and set the table width to 100%
or to some fixed value.
Conclusion
As pointed out in the above sections, overflow-wrap
and word-break
are similar in so many ways, and you can use both of them for line-breaking controls. The name overflow-wrap
is an alias of the legacy word-wrap
property. Therefore, you can use the two interchangeably. However, it is worth mentioning that the browser support for the newer overflow-wrap
property is still low. You are better off using word-wrap
instead of overflow-wrap
if you want near-universal browser support.
According to the draft CSS3 specification, browsers and user agents should continue supporting word-wrap
for legacy reasons. If you are looking to manage content overflow, overflow-wrap
or its legacy name word-wrap
might be sufficient. You can also use word-break
to break a word between two characters if the word overflows its container. Just like overflow-wrap
, you need to tread with caution when using word-break
because of limitations in the browser support.
Now that you know the behavior associated with the two properties, you can decide where and when to use them. Did I miss anything? Leave a comment in the comments section. I will be happy to update this article.
Is your frontend hogging your users’ CPU?
As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/
LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.
Modernize how you debug web and mobile apps — Start monitoring for free.
От автора: в наши дни очень важно сделать сайт адаптивным, чтобы он правильно отображался на всех устройствах. К сожалению, несмотря на все усилия, вы все равно можете получить неработающие макеты. Иногда макеты нарушаются из-за того, что некоторые слова слишком длинные, чтобы уместиться в контейнере.
Переполнение контента может произойти, когда вы имеете дело с пользовательским контентом, который вы не можете контролировать. Типичный пример — раздел комментариев в блоге. Следовательно, вам необходимо применить соответствующий стиль, чтобы содержимое не переполняло свой контейнер.
Вы можете использовать свойства CSS word-wrap, overflow-wrap или word-break для обертывания или переноса слов, которые в противном случае переполнили бы их контейнер. Эта статья представляет собой подробное руководство по свойствам CSS word-wrap, overflow-wrap и word-break, а также о том, как вы можете использовать их, чтобы не допустить, чтобы переполнение содержимого разрушало ваш красиво оформленный макет.
Прежде чем мы начнем, давайте разберемся, как браузеры переносят контент в следующую секцию.
Как происходит перенос контента в браузерах?
Браузеры выполняют перенос содержимого в разрешенные брейкпоинты, называемый «мягкой оберткой». Браузер будет обертывать контент с использованием мягкой обертки, если таковая возможна, чтобы минимизировать переполнение контента.
В английской и большинстве подобных ей системах письма возможности мягкой обертки по умолчанию появляются на границах слов при отсутствии переносов. Поскольку слова ограничены пробелами и знаками препинания, именно здесь используются мягкие обертки.
Хотя в английских текстах для символов пробела используются мягкие обертки, для неанглийских систем письма ситуация может быть иной. Некоторые языки не используют пробелов для разделения слов. Следовательно, упаковка содержимого зависит от языка или системы письма. Значение атрибута 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, слово переполняет свой контейнер. Это является поведением системы при переносе строк по умолчанию.
Anywhere
Использование значения в аnywhere приведет к разрыву неразрывной строки в произвольных точках между двумя символами. Аnywhere не будет добавлять символ дефиса, даже если вы примените свойство hyphens к этому элементу.
Браузер разорвет слово только в том случае, если отображение слова приведет к переполнению. Если слово вызывает переполнение, оно будет разорвано в точке, где это переполнение произошло.
Когда вы используете аnywhere, браузер будет учитывать возможности мягкого переноса, предоставляемые разрывом слова, при вычислении внутренних размеров min-content:
.my-element{ overflow-wrap: anywhere; } |
В отличие от предыдущего примера, где мы использовали overflow-wrap: normal, на изображении ниже мы используем overflow-wrap :where. Слово-переполнение, которое невозможно разбить, разбивается на фрагменты текста с помощью overflow-wrap: anywhere, чтобы оно поместилось в своем контейнере.
Значение anywhere не поддерживается некоторыми браузерами. На изображении ниже показана поддержка браузерами по данным caniuse.com. Поэтому не рекомендуется использовать overflow-wrap: anywhere, если вы хотите иметь более высокую поддержку браузера.
Break-word
Значение break-word похоже на любое другое с точки зрения функциональности. Если браузер может перенести слово без переполнения, то он это сделает. Однако, если слово все еще переполняет контейнер, даже когда оно находится в новой строке, браузер разделит его в точке, где снова произошло бы переполнение:
.my-element{ overflow-wrap: break-word; } |
На изображении ниже показано, как браузер прерывает переполненный текст в предыдущем разделе, когда вы применяете overflow-wrap: break-word. Вы заметите, что изображение ниже выглядит так же, как изображение в последнем примере. Разница между overflow-wrap: anywhere и overflow-wrap: break-word заключается в вычислении внутренних размеров min-content.
Разница между 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-break
Word-break — еще одно свойство CSS, которое вы можете использовать для указания возможности мягкого переноса между символами. Вы можете использовать это свойство, чтобы разбить слово в том месте, где могло произойти переполнение, и перенести его на следующую строку.
Ниже приводится то, что говорится о свойстве CSS word-break в спецификации 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 к блоку текста, который содержит слово длиннее, чем его контейнер. Вы видите, что в браузере действуют обычные правила разбиения на слова.
Break-all
Значение break-all вставит разрыв строки именно в том месте, где текст переполнился бы для некитайских, неяпонских и некорейских систем письма. Слово не будет помещено в отдельную строку, даже если это предотвратит необходимость вставки разрыва строки:
.my-element{ word-break: break-all; } |
На изображении ниже я применил стиль word-break:break-all к элементу p шириной 240 пикселей, содержащему переполненный текст. Браузер вставил разрыв строки в точке, где могло произойти переполнение, и перенес оставшийся текст в следующую строку.
Использование break-all приведет к разрыву слова между двумя символами именно в том месте, где произойдет переполнение в английском и других родственных языковых системах. Однако это не применимо к текстам на китайском, японском и корейском языках (CJK).
Он не применяет то же поведение к текстам CJK, потому что системы письма CJK имеют свои собственные правила для применения брейкпоинтов. Создание разрыва строки между двумя символами произвольно во избежание переполнения может значительно изменить общий смысл текста. Для систем CJK браузер будет применять разрывы строк в том месте, где такие разрывы разрешены.
На изображении ниже показана поддержка браузером word-break: break-word согласно caniuse.com. Хотя последние версии современных веб-браузеров поддерживают это значение, поддержка среди некоторых мобильных браузеров неизвестна.
Keep-all
Если вы используете значение keep-all, браузер не будет применять разрывы слов к текстам CJK, даже если происходит переполнение содержимого. Эффект от применения значения keep-all такой же, как и у normal для систем письма, отличных от CJK:
.my-element{ word-break: keep-all; } |
На изображении ниже применение word-break: keep-all имеет тот же эффект, что и word-break: normal, потому что я использую систему письма, отличную от CJK (английский язык).
На изображении ниже показана поддержка браузером word-break: keep-all согласно caniuse.com. Это значение поддерживается в большинстве популярных десктопных браузеров. К сожалению, это не относится к мобильным браузерам.
Теперь, когда мы рассмотрели свойства 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, Яндекс.Дзен
Example
Allow long words to be able to break and wrap onto the next line:
div {
word-wrap: break-word;
}
Try it Yourself »
Definition and Usage
The word-wrap
property allows long words to be able to be broken and wrap
onto the next line.
Show demo ❯
Default value: | normal |
---|---|
Inherited: | yes |
Animatable: | no. Read about animatable |
Version: | CSS3 |
JavaScript syntax: | object.style.wordWrap=»break-word» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Property | |||||
---|---|---|---|---|---|
word-wrap | 4.0 | 5.5 | 3.5 | 3.1 | 10.5 |
CSS Syntax
word-wrap: normal|break-word|initial|inherit;
Property Values
Value | Description | Demo |
---|---|---|
normal | Break words only at allowed break points. This is default | Demo ❯ |
break-word | Allows unbreakable words to be broken | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
Related Pages
CSS tutorial: CSS Text Effects
This CSS tutorial explains how to use the CSS property called word-wrap with syntax and examples.
Description
The CSS word-wrap property defines whether the browser is allowed to line break within words when a word is too long to fit within its container.
Syntax
The syntax for the word-wrap CSS property is:
word-wrap: value;
Parameters or Arguments
- value
-
The amount of extra space to display between words (in addition to the standard spacing for the font). It can be one of the following:
Value Description break-word Words may be broken arbitrarily when a word is too long to fit within its container
p { word-wrap: break-word; }normal Only normal word break points are allowed
p { word-wrap: normal; }
Note
- If the word-wrap property is expressed as a fixed value, it can be either a positive or negative value.
- A positive value would add additional space between words (in addition to standard spacing for the font).
- A negative value would remove space between words.
- If the word-wrap property is set to normal, the selected font would determine the space between words.
- See also the overflow and overflow-x properties.
Browser Compatibility
The CSS word-wrap property has basic support with the following browsers:
- Chrome
- Firefox (Gecko)
- Internet Explorer 5.5+ (IE 5.5+)
- Opera 10.5+
- Safari (WebKit)
Example
We will discuss the word-wrap property below, exploring examples of how to use this property in CSS.
Normal
Let’s look at an example where we set the word-wrap property to normal.
The CSS would look like this:
p { word-wrap: normal; width: 125px; background: lightblue; padding: 5px; }
The HTML would look like this:
<div>
<p>This paragraph was written by techonthenet.com and contains the word, antidisestablishmentarianism, to demonstrate how to handle word breaking.</p>
</div>
The result would look like this:
In this CSS word-wrap example, line breaks are inserted only at normal word break points. So if a word is too long to fit within its container, it will overflow. As you can see the word antidisestablishmentarianism is too long to fit so part of it overflows the container.
Break-Word
Now let’s see what happens when we use this same example and set the word-wrap property to break-word.
The CSS would look like this:
p { word-wrap: break-word; width: 125px; background: lightblue; padding: 5px; }
The HTML would look like this:
<div>
<p>This paragraph was written by techonthenet.com and contains the word, antidisestablishmentarianism, to demonstrate how to handle word breaking.</p>
</div>
The result would look like this:
In this CSS word-wrap example, the browser is allowed to break words arbitarily when the word is too long to fit within its container. So in the example of the word antidisestablishmentarianism, the line break is inserted between «antidisestablishme» and «ntarianism» instead of overflowing the container.
The word-wrap
property is used to specify whether lines can break inside words that are so long that they would overflow their container and that are otherwise not breakable by default.
How is it different from the word-break
property? Well, the word-break
property breaks a line in between two characters of a word which comes at the end of this line, to make the whole line fit inside its container. But the word-wrap
property, on the other hand, breaks a word when the word itself takes up an entire line and overflows that line; that is, when the word itself and on its own is too long that it would overflow its container, so we make it wrap just line a line would wrap to fit inside its container.
The word-wrap
property only has an effect when white-space
allows wrapping.
The word-wrap
property is called overflow-wrap
in the CSS Text Level 3 specification (which is still a Working Draft so things may change).
Trivia & Notes
The two properties (word-break
and word-wrap
) differ rules and overflow of words: as mentioned earlier, word-wrap
is used to break words that overflow their container, while the word-break
property breaks all words at the end of a line, even those that would normally wrap onto another line and wouldn’t overflow their container.
No hyphenation character is inserted at the break point of the word. Because of that, it would be wiser to use this property in conjunction with the hyphens
property.
Official Syntax
-
Syntax:
word-wrap: normal | break-word
- Initial: normal
- Applies To: all elements
- Animatable: no
Values
- normal
- lines may only break at normal word break points.
- break-word
- normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line.
Examples
The following line will break all words (inside paragraphs) that are too long and would normally overflow their container.
p { word-wrap: break-word; }
Browser Support
Mobile / Tablet
- 7.0
- 4.4
- all
- 111
- 110
* denotes prefix required.
- Supported:
- Yes
- No
- Partially
- Polyfill
Stats from caniuse.com
Note: This article is focused on the semantics of the English Language as the Writing System. Other systems, especially CJK (Chinese Japanese Korean) have conventions and overflow requirements that vary from English and are out of the scope of this article.
Text Wrapping
In CSS, overflow is the scenario when the content inside a fixed-width container, is wider than the container’s width. The default behavior of CSS is to render the content flowing out of the container. This may look ugly but this helps the developer see the issue and fix it — instead of the issue getting hidden which can cause potential missing information for the user. For example, a form submission button overflowing and becoming inaccessible. So to avoid such issues, CSS by default prevents Data Loss.
Content overflowwwwwwwwwww
CSS offers multiple capabilities to fix this issue.
Property: overflow-wrap (alias word-wrap)
This property applies to inline elements. It determines whether the browser should break an otherwise unbreakable string to avoid it from overflowing its parent’s width.
It has the following possible keyword values.
- normal
- Anywhere
- break-word
overflow-wrap: normal
When set to normal, the browser will break the string on default/natural opportunities, such as a blank space or a hyphen (‘-’) character. It will also leverage soft-hyphen entity ­
to break.
This is the initial value of the overflow-wrap
property. So by default, every string will be broken at soft wrap opportunities, if any, on overflow.
This is how ‘ContentOverflowing’ and ‘Content-Overflowing’ will be handled.
ContentOverflowing
Content-Overflowing
overflow-wrap: anywhere;
This value allows the browser to break the string anywhere to avoid overflow.
Consider the following scenario with the default overflow-wrap: normal;
value for a fixed-width container.
ContentOverflow
There is no blank space, a hyphen, or any other soft wrap opportunity in the string. Therefore, it overflows. If we apply overflow: anywhere;
, we get the following, wrapped result.
ContentOverflow
overflow-wrap: break-word;
It behaves the same as overflow-wrap: anywhere;
. The difference is that the former does not consider soft-wrap opportunities when calculating min-content intrinsic sizes. In case you have not explored extrinsic vs intrinsic sizing, Ahmed Shadeed provides a great resource. It breaks only those words which have a width smaller than the available width.
Content is Overflowing
Property: word-break
CSS offers another property, word-break for handling the same issue — overflows.
It has the following keyword values
- normal
- break-all
- keep-all
- break-word
word-break: normal;
Words will break at the default rules — such as a blank space, a hyphen, etc.
This is how ‘ContentOverflow’ and ‘Content-Overflow’ will be handled.
ContentOverflow
Content-Overflow
word-break: break-all;
Break the word at the point it overflows. It does not take into account if placing the overflowing word onto the next line will eliminate the overflow in the first place or not. This doesn’t apply to CJK writing systems.
ContentOverflow
word-break: keep-all;
For Non-CJK systems, the behavior is the same as word-break: normal
.
ContentOverflow
word-break: break-word;
It has the same effect that word-break: normal;
and overflow-wrap: anywhere;
has. But unlike word-break: break-all;
, it takes into account if placing the overflowing word onto the next line will eliminate the overflow.
For example, let’s see how word-break: break-word;
handles the following scenario:
Content is Overflowing Again
We observe that the whole word ‘Overflowing’ was moved onto the next line instead of breaking as it can fit the available width without overflowing. If we apply word-break: break-all;
to it, this is what we get:
Content is Overflowing Again
The word ‘Overflowing’ was broken at exactly the point where it otherwise caused the overflow. And it was not considered if moving it onto the next line eliminated the overflow or not.
overflow-wrap vs word-break
At a high level, both properties solve the same issue. But, a key difference lies in how both the properties approach the issue and the subtle aesthetic variation in their outcomes.
To visualize, consider a fixed and short-width container for the test “A Very LongWordThatHasNoBreakingPossibilities”.
A Very LongWordThatHasNoBreakingPossibilities
Let’s solve the overflow with overflow-wrap: break-word;
.
A Very LongWordThatHasNoBreakingPossibilities
Now, let’s solve it with word-break: break-all;
.
A Very LongWordThatHasNoBreakingPossibilities
Notice the difference? word-break: break-all;
breaks the word even if placing the word on the next line would eliminate the need for breaking. This prevents large gaps before the breaks — and produces visually better results. The difference is more clearly visible in the overflow-wrap: anywhere;
vs word-break: break-all;
case. A case of the apparently twin properties. Consider you have a very short space to squeeze in a checkbox and a text which can not fit on the same line without overflowing. This is how the outcome looks like with overflow-wrap: anywhere;
:
Photosynthesis
We observe that a lot of real estate beside the checkbox has been left unutilized. A better fix is provided by word-break: break-all;
:
Photosynthesis
As observed, word-break
discards the possibility of the word fitting the next line and prefers optimizing the usage of available real estate — this is often the better adjustment visually.
The above example receives its inspiration from MDN’s resource on text wrapping.
Summary
Property | Value | Behavior | When To Use | Example |
---|---|---|---|---|
overflow-wrap |
|
Break at natural line breakpoints such as blank space, a hyphen | When overflow is determined to not be a possibility |
Content |
anywhere |
Break between any 2 characters where the overflow occurs and consider soft wrap opportunities when calculating the min-content intrinsic sizes | When overflow should be handled by breaking long words. As discussed, the alternative option of word-break: break-all; produces visually better results |
ContentOverflow |
|
break-word |
Break between any 2 characters but do not consider soft wrap opportunities when calculating the min-content intrinsic sizes | When overflow should be handled by breaking only those words which have a width smaller than the available width |
Content is Overflowing |
|
word-break |
normal |
Break at default rules | When overflow is determined to not be a possibility |
Content |
break-all |
Break exactly where the content overflows | When overflow should be handled by breaking text exactly at the point of overflow — even if placing the word on a new line eliminates the overflow |
Content is Overflowing Again |
|
break-word |
Same as word-break: normal; and overflow-wrap: anywhere; — Break can create gaps unlike word-break: break-all; |
When placing the overflowing word onto the next line eliminates overflow. This can cause gaps. |
Content is Overflowing Again |
Examples
Here are examples from the above summary in a codepen to help demonstrate what the CSS code should look like:
<section class="centered"> <h2>Without Handling Overflow</h2> <div>Content with aVeryVeryVeryLongWord</div> <!----> <h2>Handling Overflow with overflow-wrap</h2> <h3>overflow-wrap: normal;</h3> <div class="ow-normal">Content with aVeryVeryVeryLongWord</div> <h3>overflow-wrap: anywhere;</h3> <div class="ow-anywhere">Content with aVeryLongWordThatDoesNotFit</div> <h3>overflow-wrap: break-word;</h3> <div class="ow-break-word">Content with aVeryLongWordThatDoesNotFit</div> <!----> <h2>Handling Overflow with word-break</h2> <h3>word-break: normal;</h3> <div class="wb-normal">Content with aVeryVeryVeryLongWord</div> <h3>word-break: break-all;</h3> <div class="wb-break-all">Content with aVeryLongWordThatDoesNotFit</div> <h3>word-break: break-word;</h3> <div class="wb-break-word">Content with aVeryLongWordThatDoesNotFit</div> </section>
* { font-family: sans-serif; } section.centered { text-align: center; } div { display: inline-block; width: 130px; border: 3px solid #48abe0; text-align: left; } .ow-normal { overflow-wrap: normal; } .ow-anywhere { overflow-wrap: anywhere; } .ow-break-word { overflow-wrap: break-word; } .wb-normal { word-break: normal; } .wb-break-all { word-break: break-all; } .wb-break-word { word-break: break-word; } h3 { font-weight: normal; font-style: italic; border-top: 1px solid #b5b5b5; width: 30%; margin-left: auto; margin-right: auto; margin-top: 20px; padding-top: 20px; }
Conclusion
This article has scratched the surface of text-wrapping. Wrapping in itself is a deeper topic as it is tightly coupled to the semantics of the target language. Moreover, it is becoming common to offer web content in multiple languages — aka Internatiolaisation/ Localisation — which makes learning it more important than before for the developers.