CSS word wrapping
CSS Word Wrap
In CSS, we can use the white-space
property to control how text wraps. By default, text wraps when necessary to fit the container width. However, sometimes you may want text to not wrap at all, or to wrap at a specific location. Below, we’ll detail how to control text wrapping using CSS.
The white-space property
The white-space
property specifies how white space within an element is handled. It has the following values:
normal
: Default value, collapses spaces and line breaks, and wraps when necessary.nowrap
: Collapses spaces and line breaks, but does not wrap.pre
: Preserves spaces and line breaks, but does not automatically wrap.pre-line
: Collapses spaces, preserves line breaks, and may automatically wrap.pre-wrap
: Preserves spaces and line breaks, but may automatically wrap.
No Line Break
If we do not want text to wrap at all, we can set the white-space
property to nowrap
. The sample code is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
p {
white-space: nowrap; }
</style>
</head>
<body>
<p>This is a long sentence that should not be broken.</p>
</body>
</html>
In the above code, the text within the <p>
element does not wrap. Instead, it scrolls horizontally to fit the container width when necessary. As shown below:
This is a long sentence that should not be broken.
Preserve Line Breaks
Sometimes, we want to preserve line breaks within text and automatically wrap it when necessary. To do this, we can use the pre-line
value of the white-space
property. The sample code is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
p {
white-space: pre-line;
}
</style>
</head>
<body>
<p>This is a text with
line breaks in it.</p>
</body>
</html>
In the above code, the text within the <p>
elements retains line breaks but automatically wraps. As shown below:
This is a text with
line breaks in it.
Preserve Line Breaks and Whitespace
Sometimes, we may need to completely preserve line breaks and whitespace within text without collapsing them. To do this, use the pre
or pre-wrap
values of the white-space
property. The sample code is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
p {
white-space: pre;
}
</style>
</head>
<body>
<p>This is a text with
multiple
spaces.</p>
</body>
</html>
In the above code, the text within the <p>
element will retain line breaks and whitespace within the text, but will not automatically wrap. As shown in the following figure:
This is a text with
multiple
spaces.
Summary
By using the white-space
attribute, we can flexibly control text wrapping. Choosing the appropriate value based on actual needs can help us better display text content.