How do I control how text wraps?
Author: Deron Eriksson
Description: This CSS tutorial describes how the white-space property can be used to control how text wraps.
Tutorial created using: Windows XP


The 'white-space' property can be used to control how text wraps in an element. I find this most useful in table cells when I want to make sure that text wraps in what I consider to be the correct place.

When white-space is set to 'normal', text in an element wraps normally and whitespace gets collapsed. When white-space is set to 'nowrap', whitespace collapses normally, but text does not wrap since line breaks are suppressed. When white-space is set to 'pre', white-space is not collapsed, and lines only break at line breaks in the source code.

The style-test.html page demonstrates the white-space property set to normal, nowrap, and pre in three table cells and then in three div elements.

style-test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Style Test</title>
<style type="text/css">
table {
	border: 2px solid black;
	width: 140px;
	margin-bottom: 1em;
}
td {
	border: 1px solid black;
}
div {
	border: 1px solid black;
	margin-bottom: 1em;
}
</style>
</head>
<body>


<table>
	<caption>'white-space: normal' on first cell</caption>
	<tr>
		<td style="white-space: normal">Blah blah blah
blah</td>
		<td>Blah blah blah blah</td>
	</tr>
</table>
<table>
	<caption>'white-space: nowrap' on first cell</caption>
	<tr>
		<td style="white-space: nowrap">Blah blah blah
blah</td>
		<td>Blah blah blah blah</td>
	</tr>
</table>
<table>
	<caption>'white-space: pre' on first cell</caption>
	<tr>
		<td style="white-space: pre">Blah blah blah
blah</td>
		<td>Blah blah blah blah</td>
	</tr>
</table>

<div style="white-space: normal;">Here     we have some text that is going to wrap (white-space: normal)</div>
<div style="white-space: nowrap;">Here     we have some text that will not wrap (white-space: nowrap)</div>
<div style="white-space: pre;">Here     we have some 
text that will only wrap at linefeeds (white-space: pre)</div>

</body>
</html>

Here we can see a screen capture of style-test.html displayed in IE7. In the second table, notice how the first cell is expanded since its white-space value is 'nowrap'. In the third table, notice how the first cell wraps after the third 'blah', since this is where we have our linefeed in our source code. Another interesting thing to notice is the whitespace in the third div element. Notice that the whitespace between 'Here' and 'we' hasn't been collapsed, since the white-space value for the third div element is 'pre'.

examples of controlling how text wraps using the white-space property