How to Wrap Words in a <div> Tag with CSS
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.
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-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
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>