Word wrap break word in div

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's user avatar

trejder

17k27 gold badges123 silver badges215 bronze badges

asked Jul 18, 2009 at 15:56

Satya Kalluri's user avatar

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 Alavi's user avatar

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

lukaserat's user avatar

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's user avatar

Tunaki

131k46 gold badges330 silver badges415 bronze badges

answered Jul 18, 2009 at 16:13

Kim Stebel's user avatar

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.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa​aaaaaaaaaaaaaaaaaaaaaaaaaaaaa

code's user avatar

code

5,1204 gold badges16 silver badges37 bronze badges

answered Jul 18, 2009 at 16:14

Orr Siloni's user avatar

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

Amol's user avatar

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.

Radek Postołowicz's user avatar

answered Apr 12, 2013 at 13:56

Kyle Dearle's user avatar

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 8)

answered Oct 14, 2014 at 15:59

Andrew Marais's user avatar

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+ */
}

Community's user avatar

answered Apr 20, 2015 at 9:21

Timeless's user avatar

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 Alwis's user avatar

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

Juraj Guniš's user avatar

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's user avatar

John Slegers

44.5k22 gold badges201 silver badges169 bronze badges

answered Feb 6, 2016 at 17:06

Wesson2's user avatar

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's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

answered May 23, 2012 at 9:53

Swapnil Godambe's user avatar

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

Vladimir Salguero's user avatar

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's user avatar

Stephen Rauch

47.2k31 gold badges110 silver badges133 bronze badges

answered Sep 18, 2018 at 2:24

Rahul Wasnik's user avatar

1

you can use this CSS

p {
  width: min-content;
  min-width: 100%;
}

answered Dec 27, 2019 at 10:22

Rashid Iqbal's user avatar

Rashid IqbalRashid Iqbal

1,05313 silver badges12 bronze badges

Try this CSS property —

overflow-wrap: anywhere;

answered Jun 9, 2022 at 6:12

Akshay Chavan's user avatar

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

deshbanks's user avatar

1

Try this

div {display: inline;}

answered Jul 18, 2018 at 16:58

Michael Mulikita's user avatar

try:

overflow-wrap: break-word;

borchvm's user avatar

borchvm

3,48411 gold badges45 silver badges43 bronze badges

answered Jan 29, 2020 at 3:00

Eden Sharvit's user avatar

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's user avatar

JSuar

21.1k4 gold badges43 silver badges82 bronze badges

answered Jan 27, 2011 at 8:36

aks's user avatar

1

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 guide explains the various ways in which overflowing text can be managed in CSS.

What is overflowing text?

In CSS, if you have an unbreakable string such as a very long word, by default it will overflow any container that is too small for it in the inline direction. We can see this happening in the example below: the long word is extending past the boundary of the box it is contained in.

CSS will display overflow in this way, because doing something else could cause data loss. In CSS data loss means that some of your content vanishes. So the initial value of overflow is visible, and we can see the overflowing text. It is generally better to be able to see overflow, even if it is messy. If things were to disappear or be cropped as would happen if overflow was set to hidden you might not spot it when previewing your site. Messy overflow is at least easy to spot, and in the worst case, your visitor will be able to see and read the content even if it looks a bit strange.

In this next example, you can see what happens if overflow is set to hidden.

Finding the min-content size

To find the minimum size of the box that will contain its contents with no overflows, set the width or inline-size property of the box to min-content.

Using min-content is therefore one possibility for overflowing boxes. If it is possible to allow the box to grow to be the minimum size required for the content, but no bigger, using this keyword will give you that size.

Breaking long words

If the box needs to be a fixed size, or you are keen to ensure that long words can’t overflow, then the overflow-wrap property can help. This property will break a word once it is too long to fit on a line by itself.

Note: The overflow-wrap property acts in the same way as the non-standard property word-wrap. The word-wrap property is now treated by browsers as an alias of the standard property.

An alternative property to try is word-break. This property will break the word at the point it overflows. It will cause a break-even if placing the word onto a new line would allow it to display without breaking.

In this next example, you can compare the difference between the two properties on the same string of text.

This might be useful if you want to prevent a large gap from appearing if there is just enough space for the string. Or, where there is another element that you would not want the break to happen immediately after.

In the example below there is a checkbox and label. Let’s say, you want the label to break should it be too long for the box. However, you don’t want it to break directly after the checkbox.

Adding hyphens

To add hyphens when words are broken, use the CSS hyphens property. Using a value of auto, the browser is free to automatically break words at appropriate hyphenation points, following whatever rules it chooses. To have some control over the process, use a value of manual, then insert a hard or soft break character into the string. A hard break () will always break, even if it is not necessary to do so. A soft break (&shy;) only breaks if breaking is needed.

You can also use the hyphenate-character property to use the string of your choice instead of the hyphen character at the end of the line (before the hyphenation line break).

This property also takes the value auto, which will select the correct value to mark a mid-word line break according to the typographic conventions of the current content language.

The <wbr> element

If you know where you want a long string to break, then it is also possible to insert the HTML <wbr> element. This can be useful in cases such as displaying a long URL on a page. You can then add the property in order to break the string in sensible places that will make it easier to read.

In the below example the text breaks in the location of the <wbr>.

See also

  • The HTML <wbr> element
  • The CSS word-break property
  • The CSS overflow-wrap property
  • The CSS white-space property
  • The CSS hyphens property
  • Overflow and Data Loss in CSS

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, and word-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 and overflow-wrap CSS properties
    • Normal
    • Anywhere
    • Break-word
  • Implementing the Word-break CSS property
    • Setting word-break to Normal
    • The Break-all value
    • Using the Keep-all value
  • What is the difference between overflow-wrap and word-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:

CSS Overflow-Wrap Compatibility

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:

CSS Break-Word Compatibility

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:

CSS Keep-all Compatibility

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:

Using Chrome DevTools With CSS

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.LogRocket Dashboard Free Trial Bannerhttps://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.

Example of A Guide To CSS Text Wrapping

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.

  1. normal
  2. Anywhere
  3. 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 &shy; 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

  1. normal
  2. break-all
  3. keep-all
  4. 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

This table shows a summary of the CSS text wrapping properties

Property Value Behavior When To Use Example
overflow-wrap

normal

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.

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

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

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

Вы можете использовать свойства 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, слово переполняет свой контейнер. Это является поведением системы при переносе строк по умолчанию.

Полное руководство по 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:

Это свойство определяет возможности мягкого переноса между буквами, то есть там, где это «нормально» и допустимо для разрывов строк текста. 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, Яндекс.Дзен

How to wrap text in cssThe CSS word wrap property will help you break long words and wrap them to the next line. Usually, it is a great way of preventing overflow when a string becomes too long to remain inside its container. In this guide, you will learn how this CSS property works.

Contents

  • How to Wrap Text in CSS
  • Accepted Parameters or Values
    • – How the normal Value Works
    • – How To Use the anywhere Value
    • – How To Use the break-word Value
    • – How To Use the inherit Value
    • – Similarities and Differences Between Break-word and Anywhere Values
  • Note to Developers
    • – Example – Using the overflow-wrap Property
  • Conclusion

CSS allows you to break long words using the word-wrap property and CSS text wrapping them onto the next line. The property helps you avoid strangely long strings of text that may result in overflow issues. By using it, you let the browser know that it can break a line within an element into multiple lines in otherwise unbreakable places.

The syntax for the property is:

#element
{
word-wrap: value;
}

Accepted Parameters or Values

The word-wrap property accepts the following CSS text wrap parameters:

  • normal – It is the default value that allows a browser to break lines depending on the normal rules of breaking a line. In the case of unbroken strings or words, it will not break them even when they overflow their containers.
  • break-word – The value breaks strings or long words in arbitrary places to force strings that are too long to fit inside their containers. It does not add a hyphen even when you set the hyphen property.
  • anywhere – This value lets you break URLs or long strings at any point if the text does not have an acceptable breakpoint. However, the value will not add a hyphen even when you define it.
  • inherit – With this value, you let the word-wrap property inherit the value set in the immediate parent element.
  • initial – It allows the property to use its default value.

– How the normal Value Works

If you set the word-wrap property to normal, you will be letting the browser use the default line-breaking behavior. In English and related writing systems, a line break happens where there is a hyphen or white space.

Therefore, when you use the normal parameter, the strings or long words break at allowable places such as spaces between words, full stops, or comma separation. The value will not break long strings even when they cross the boundary of their container.

Example – Using the normal Value

Suppose you are creating the homepage for a local barbershop. Within the page, you decide to use a <div> tag to display the welcome message and a brief introduction. After this, you decide to set the word-wrap property to normal.

To get started, you need to create the content in the <div> tag in HTML like so:

<div id=”wordwrap”>
<h1>Welcome to 001 Barbershop</h1>
<p> Here we give you all the attention and service you deserve. Sit down, relax, and enjoy our services and products.
<br><br>
Thistextistoolongfornogoodreason
</p>
<br><br>
</div>

Next, use CSS to position the <div> tag at the center, add a border, set background color, and define the height and width of the div element. Moreover, remember to set the word-wrap property to normal. Here is how you can accomplish this in CSS:

#wordwrap
{
position: relative;
left: 50%;
border: solid blue 5px;
text-align: center;
background-color: orange;
width: 200px;
height: 300px;
word-wrap: normal;
}

In this example, you will notice there is a word that is longer than the container. The latter happens because the word does not provide a soft wrap opportunity and the value of the word-wrap property is normal. Thus, the word overflows the <div> container. This is a clear notion of the default line-breaking behavior.

– How To Use the anywhere Value

In CSS, this value will break a string if showing it in its line will overflow its container. When the string still overflows the container when placed in its line, the “anywhere” parameter will break the string at the point where the overflow would happen.

It is a new value that lets you break an otherwise unbreakable string at arbitrary places provided there are no acceptable breakpoints. The value helps address the compatibility issues associated with the “break-word” value.

When using the “anywhere” value, the browser will take into account the soft wrap opportunities brought by the word break as it calculates the min-content intrinsic sizes.

Example – Using the Anywhere Value

Suppose you want to make sure everything in the <div> tag on the barbershop landing page fits within the container. Wrap text in the <div> element using the “anywhere” parameter. Here is an example of how CSS wrap text in div works:

#wordwrap
{
position: relative;
left: 50%;
border: solid blue 5px;
text-align: center;
background-color: orange;
width: 200px;
height: 300px;
word-wrap: anywhere;
}

In other words, the value will break all the long strings to ensure they fit in the <div> element.

– How To Use the break-word Value

With the break-word value, you give the browser the liberty to wrap the overflowing word into its container without overflowing. However, when the word overflows the container when it is still on its line, the browser is going to break it at the point where the overflow would occur.

Example – Using the Break-word Value

Suppose you want to ensure that the content in the <div> tag does not overflow the container. Using the barbershop landing page example, you can ensure this by breaking any word that overflows the div container. Here is an example of how you can make text wrap in CSS with ease:

#wordwrap
{
position: relative;
left: 50%;
border: solid blue 5px;
text-align: center;
background-color: orange;
width: 200px;
height: 300px;
word-wrap: break-word;
}

In this example, you will notice that the overflowing word is broken to fit in its container. With the break-word value, the browser no longer considers soft wrap opportunities as it calculates the min-content intrinsic sizes.

– How To Use the inherit Value

With this value, you get to set the word-wrap property for a child element to be the same as that of the immediate parent. Keep in mind that it will not work with long strings unless you use the “break-word” value in the parent element.

Example – Using the Inherit Value

Say the barbershop owners want you to add another paragraph in the <div> tag. In this new paragraph, they want you to use a similar word-wrap value to the parent div element. In CSS, you can accomplish this like so:

#wordwrap
{
position: relative;
left: 50%;
border: solid blue 5px;
text-align: center;
background-color: orange;
width: 200px;
height: 300px;
word-wrap: break-word;
}
p
{
word-wrap: inherit;
}

– Similarities and Differences Between Break-word and Anywhere Values

Both of these values break a string into pieces in arbitrary points in order for it to fit inside its container and avoid overflowing. Moreover, they do not add a hyphen where they break the string even if you set it.

When you set the word-wrap property to “anywhere”, you let the browser consider soft wrap as it calculates the minimum content size. However, the “break-word” value does not consider soft wrap when calculating the minimum content size.

Example – Showing the Difference Between anywhere and break-word Values

Suppose the barbershop owners want the website to welcome each member with a message. You can use either anywhere or break-word value to wrap the welcome message. For example, you can display “Welcome David” to David.

First, here is the HTML code for the example:

<div id =”anywhere”> Welcome David (anywhere)</div>
<div id =”break-word”> Welcome David (break-word)</div>

Now, here is the CSS to display the message and wrap it using the different parameters.

div
{
display: inline-block;
width: min-content;
padding: 15px;
border: solid orange;
vertical-align: top;
}
#anywhere
{
word-wrap: anywhere;
}
#break-word
{
word-wrap: break-word;
}

You will notice that the “anywhere” parameter considers the minimum width of the element to be the width after breaking each word. On the other hand, the “break-word” parameter calculates the declared element using the default minimum width rule.

Note to Developers

Please note that the word-wrap property is the legacy name for the overflow-wrap property. The latest browsers are implementing CSS text overflow wrap to allow browsers to break a long string at otherwise unacceptable points in a line as a way of avoiding overflow. For compatibility, they are treating word-wrap as an alias for the overflow-wrap property.

You can use any of these properties in CSS to wrap text since they behave the same way. What’s more, the overflow-wrap property accepts the same parameters as the word-wrap property.

The syntax for the overflow-wrap property is:

overflow-wrap: normal | break-word | anywhere | initial | inherit;

However, if you want browser support that is almost universal, then the word-wrap property is better off compared to the overflow-wrap property. For legacy reasons, browsers are still supporting the word-wrap property.

– Example – Using the overflow-wrap Property

Suppose you now decide to use the overflow-wrap property to display a welcome message to visitors of your barbershop website. Here is how you can accomplish this:

#wordwrap
{
position: relative;
left: 50%;
border: solid blue 5px;
text-align: center;
background-color: orange;
width: 200px;
height: 300px;
overflow-wrap: break-word;
}

Conclusion

The word-wrap property in CSS provides you with a unique way of wrapping text to prevent it from overflowing its container. In this guide, you learned how to use the property and its parameters. Here is a recap:

  • CSS lets you use either word-wrap or overflow-wrap to break long strings
  • The two properties share the same parameters or values; parameters include normal, break-word, anywhere, initial, and inherit
  • The normal and initial parameters refer to the default values
  • Using the inherent value allows a child element to inherit the value of the immediate parent element
  • Both break-word and anywhere values allow a browser to break a long string at a rather unacceptable point to avoid overflow

Css word wrap propertyNow that you understand how to use the word-wrap property in CSS, go ahead and start using it as a professional web developer.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

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!

There are many CSS properties that can be used to control the wrapping and breakpoints and determine how spaces and line breaks must be processed before wrapping.

If you’ve faced the situation when you need to wrap words in a <div>, you can use the white-space property with the «pre-wrap» value to preserve whitespace by the browser and wrap the text when necessary and on line breaks. Also, you’ll need the word-wrap property.

In this snippet, see how to use the properties mentioned above to wrap words in a <div> with a cross-browser method.

  • Use <h1> and <div> elements.
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>Example</h1>
    <div>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </div>
  </body>
</html>
  • Set the white-space property to «pre-wrap». Also, add the -moz- and -o- prefixes.
  • Use the word-wrap property with the «break-word» value.
div {
  white-space: pre-wrap;
  white-space: -moz-pre-wrap;
  white-space: -pre-wrap;
  white-space: -o-pre-wrap;
  word-wrap: break-word;
}

The result of our code looks like the following.

Example of wrapping words in a <div> element:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        white-space: pre-wrap;
        white-space: -moz-pre-wrap;
        white-space: -pre-wrap;
        white-space: -o-pre-wrap;
        word-wrap: break-word;
        color: lightgreen;
      }
    </style>
  </head>
  <body>
    <h1>Example</h1>
    <div>
      Lorem ipsum, 
      or lipsum as it is sometimes known, is dummy text used in laying out print,
      graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century
      who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for 
      use in a type specimen book.
    </div>
  </body>
</html>

Result

Lorem ipsum,
or lipsum as it is sometimes known, is dummy text used in laying out print,
graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century
who is thought to have scrambled parts of Cicero’s De Finibus Bonorum et Malorum for
use in a type specimen book.

Let’s see another example, where we use the CSS overflow-wrap property, which applies to inline elements. It determines whether the browser must add line breaks within an otherwise unbreakable string for preventing the text from overflowing its line box.

In the example below, we wrap not only the word within a <div> element but also the word, which is placed in a <span> within the <div> element.

Example of wrapping words in a <div> element with the CSS word-wrap property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        width: 100px;
        border: 1px solid green;
        padding: 10px;
        word-wrap: break-word;
      }
      span {
        overflow-wrap: break-word;
        -webkit-hyphens: auto;
        -ms-hyphens: auto;
        hyphens: auto;
      }
    </style>
  </head>
  <body>
    <h1>Example</h1>
    <div>
      This is a <span>loooooooooooooooooooooooooong</span> text for example. Here can be a long word, tooooooooooooooo.
    </div>
  </body>
</html>

Like this post? Please share to your friends:
  • Word wrap break text
  • Word wrap and table
  • Word wow скачать бесплатно
  • Word would go out
  • Word wonder скачать игру