Long texts can appear uncontrollable during web design. But they can be unavoidable as well, and sometimes they end up crossing borders. This can create a loose Document Object Model (DOM) with an unnecessary overflow that is not user-friendly.

But here's the good news: you can deal with such long texts by wrapping them onto a new line using CSS. Here we'll show you just how to wrap long, unbroken texts with CSS.

How CSS Text Wrap Works

CSS handles stretched long words using the inbuilt word-wrap or overflow-wrap property.

However, when not controlled, browsers handle such long texts by default. They won't wrap long words until they receive the instruction to do so.

Related: What You Need to Know About the DOM

The two major CSS properties mentioned earlier work the same way and you can use them interchangeably. However, they accept four values or syntaxes:

  • break-word: This is the actual CSS syntax that tells the browser to wrap a long text over to a new line.
  • normal: It breaks each word at the normal points of separation within a DOM. It doesn't have effect on long strings.
  • initial: It's the default browser's way of handling strings. Like the normal syntax, it doesn't break long words.
  • inherit: It tells the child element to inherit the property of its parent. But it still doesn't work with long texts, except you apply break-word to the parent element.

How to Wrap Long Words Using CSS Word Wrap

Wrapping words over to a new line with CSS is easy and doesn't require cumbersome CSS tweaks to work.

For instance, the long h2 text within the text container in the sample image below crosses the border line:

Web page with div container having long h2 text

Let's see how we can wrap it onto the next line using the word-wrap CSS property:

HTML:

        <div class="wrap-it">
This-div-contains-the-long-h2-lorem-text-demonstrated-in the image above
</div">

CSS:

        .wrap-it{
word-wrap: break-word;
}

After wrapping the long h2 text in the sample image, here's the output:

Web page with div container having long h2 text wrapped onto a new line

That's it! You now know how to wrap words onto a new line within your DOM using CSS.

Related: How to Target Part of a Web Page Using CSS Selectors

However, as stated earlier, word-wrap and overflow-wrap work the same way and accept similar properties.

To use overflow-wrap instead, just replace word-wrap with it.

It's Important to Wrap Words on a Web Page

In addition to adding more aesthetics to your webpage, wrapping texts compacts the DOM. Even if you control what goes into your content section, users can post links or other words that don't fit into your text container or your entire DOM.

Therefore, applying text wrap to such a section is necessary to keep the DOM intact.