How to Wrap Words in a <div> Tag with CSS
If you’ve faced the situation when you need to wrap long words in a <div>, use the white-space property with the “pre-wrap” value and word-wrap property.
There are several CSS properties that control text wrapping, breakpoints, and how spaces and line breaks are processed.
If you need to wrap long words inside a <div>, use the white-space property with the pre-wrap value. This preserves whitespace and allows the browser to wrap text at explicit line breaks or when necessary. To handle unbreakable strings that would otherwise overflow, pair it with the overflow-wrap property (formerly word-wrap).
In this snippet, see how to use the properties mentioned above to wrap words in a <div> with a modern, cross-browser approach.
Create HTML
- 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>Add CSS
- Set the
white-spaceproperty topre-wrap. - Use the
overflow-wrapproperty with thebreak-wordvalue.
div {
white-space: pre-wrap;
overflow-wrap: break-word;
}The result of our code looks like the following.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
white-space: pre-wrap;
overflow-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
<div class="demo not-prose"> 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>
Let's see another example using the CSS overflow-wrap property. It determines whether the browser must add line breaks within an otherwise unbreakable string to prevent text from overflowing its container.
In this example, we apply wrapping to both the <div> and a <span> inside it.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
width: 100px;
border: 1px solid green;
padding: 10px;
overflow-wrap: break-word;
}
span {
overflow-wrap: break-word;
hyphens: auto;
}
</style>
</head>
<body>
<h1>Example</h1>
<div>
This is a <span>loooooooooooooooooooooong</span> text for example. Here can be a long word, tooooooooooooooo.
</div>
</body>
</html>